I have recently began to start learning C# and try to write a program that's similar to a calculator in a console. I've already done it with two integers and it worked. Now I am trying to write the code allowing more user inputs to calculate with.
The thing is, that I have stuck at spliting the string from the user-input. So let's say for example he writes:
1 + 2 * 3 - 5 I want to split it where the space happens. It should still be splitting when the user uses more than just one spaces in between. It's like the same as 1,2,,3,,,,5,6,,,4 : How can you split by the comma when there are MORE than one comma used? I only want the integers (and the operators from example 1).
I have already tried with [string_name].Split(' ') and [string_name].Split(',') but it only seems to ignore ONE char variable between the user-input-values I am interested in. That makes it impossible for me to put the values in an array and convert them to int.
Last question regarding my first example (1 + 2 * 3 - 5):
Besides accepting multiple spaces/comma, how can you split this string input efficiently, keeping int inputs and the operators? My idea was to save every uneven input value (1, 2, 3, 5) and every even input value (+, *, -,/) in an array each. I considered to put the operators into a switch with 4 cases and convert the string_array with numbers to integers. After that I would have put them all together into the exact same order like the user-input using for.
The thing is: Assuming I implement it correctly, I think that the calculation would be solved from left to right without considering the precedence of '*' and '/'.
Someone an idea how you can solve this problem with the "advanced" calculator efficiently? I have thought for a long time and tried all I could, but it doesn't seem to work ... Makes me sad a bit. I'd really like to solve this problem somehow.
Well the answer to your first question, you can pass an overload to Split that will ignore empty entries:
str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
So more traditionally, you'd want to parse the string entirely so you could handle things like parenthesis and the case where there is no space: 4*(1+2) for instance.
Related
I am trying to use the speechrecognitionengine to recognize a grammar that includes some choices from a specific set, followed by an arbitrary numeric value followed by a choice set. So "[Choice1,Choice2,Choice3] 1563 [ChoiceA,ChoiceB,ChoiceC]" Doing this with by appending a Choices array, AppendDictation() and Appending another Choices grammer works well, except that the number recognized in the AppendDictation portion comes through as "One thousand five hundred sixty-three" instead of 1563. This is counter intuitive to me because if you replace all of the above with a DictationGrammer, the number is recognized as 1563 instead of that long form example above. I would prefer to use the GrammarBuilder method with specific choice sets to increase the likelihood the right commands / phrase are recognized. Any help would be appreciated, thanks!
Also, I can't just add numbers into a Choices array because it would need to be massive due to the range of possible numbers.
Try this:
AppendDictation("spelling");
This workaround however, will not work if you say anything above 9, so for 1563 you will have to say out loud "one, five, six, three". The resulting text will be 1563.
Alternatively you could try what has been answered in this post: Converting words to numbers in PHP
Edit: Better answer in this post. Has the function to convert words into actual numbers Convert words (string) to Int
Basically for an assignment I need to create a C# program that will take a number as input (n) then create a 2D array size n*n with the numbers 1 to (n*n). It needs to use a brute force method. I have done this but at the moment the program will just randomly generate the order of the numbers each time, so it will sometimes check the same order more than once. Obviously this means it takes a really long time to check any number above 3, and even for 3 it can take a few minutes. Basically I'm wondering if there is any way for me to make it only check each order once. I am only allowed to use "basic" C# functions, so just things like *, /, +, - and nothing like .Shuffle etc.
Let me make sure I understand the question: you wish to enumerate all permutations of the numbers 1 through n squared, and check whether the permutation produces a magic square. You are now generating permutations randomly, but instead you wish to generate all permutations.
I wrote a series of articles on generating permutations; it is too long to easily summarize here.
http://ericlippert.com/2013/04/15/producing-permutations-part-one/
Choosing random order, as you found, is not a good idea.
I suggest that you put all the number 1 ... (n*n) in array , and than find all the permutation.
when you have all the permutation, it's easy to create square (1 .. n ==> the first row, n+1 ... 2n ==> the second row and so on).
Now, finding all the permutation can be done with the basic operation with recursion
I'm trying to create some sort of string-based diff algorithm on my own.
What I'm doing is: I'm iterating through every paragraph in my textdocument, comparing them both.
Now what I'm struggling with is the comparison start and end of both strings.
Consider having the two strings:
This is a test-text.
This is a very long test-text.
This means there's a change of 10 characters (9 text, 1 whitespace) in the second line ('very long ').
These characters should be highlighted accordingly. I've already come up with the solution of finding the start of the string-differences (say: index n is where the differences start):
int diffIndexStart = localText.Zip(serverText, (c1, c2) => c1 == c2).TakeWhile(b => b).Count();
Now how can I detect when the string matches again, so I can stop highlighting there, instead of highlighting the rest of the row (starting with diffIndexStart).
There's also another issue: What's when there are multiple changes within one line, let's say:
This is a test-text.
This, apparently, is a very long test-text.
Now I've got two changes: , apparently, and very long.
You're looking at the common Longest Common Subsequence (LCS) problem. There are numerous papers on that (the Wikipedia page gives some links as a start), several common approaches are highlighted in Wiki already.
I came across this question in an interview:
We have to find out the number of occurences of two given words in a text file with <=n words between them.
Example1:
text:`this is first string this is second string`
Keywords:`this, string`
n= 4
output= 2
"this is first string" is the first occurrence and number of words between this and string is 2(is, first) which is less than 4.
this is second string is the remaining string. number of words between *this and string * is 2 (is, second) which is less than 4.
Therefore the answer is 2.
I have thought that I will use
Dictionary<string, List<int>>.
My idea was that I use the dictionary and get the list of places where the particular word is repeated and then iterate through both the lists, increment the count if a condition is met and then display the count.
Is my thinking process correct? Please provide any suggestions to improve my solution.
Thanks,
Not an answer per-se (as quite honestly, I don't understand the question :P), but to add some general interview advice to the other answers:
In interviews the interviewer is always looking for the thought process and that you are a critical, logical thinker. Not necessarily that you have excellent coding recall and can compile code in your brain.
In addition interviews are a stressful process. By slowing down and talking out loud as you work things out you not only look like a better communicator and logical thinker (even if getting the question wrong), you also give yourself time to think.
Use a pen and paper, speak as you think, start off from the top and work through it. I've got jobs even if I didn't know the answers to tech questions by demonstrating that I can at least try to work things out ;-)
In short, it's not just down to technical prowess
I think it depends if the call is done only one or multiple times per string. If it's something like
int getOccurences(String str, String reference, int min_size) { ... }
then you don't really need the dictionary, not even a ist. You can just iterate through the string to find occurrences of words and then check the number of separators between them.
If on the other hand the problem is for arbitrary search/indexing, IMHO you do need a dictionary. I'd go for a dictionary where the key is the word and the value is a list of indexes where it occurs.
HTH
If you need to do that repeatedly for different pairs of words in the same text, then a word dictionary with a list of indexes is a good solution. However, if you were only looking for one pair, then two lists of indexes for those two words would be sufficient.
The lists allow you to separate the word detection operation from the counting logic.
I'm trying to make a calculator-like program where one would enter a calculation in a textbox and it would convert that calculation to an int with the result, here's what I have but it doesn't work much
string calcStr = textBox1.Text;
int result = calcStr;
Any suggestions that aren't too complicated?
If I understand the problem correct you want to be able to parse an expression like 1 + 3 + 4 from a textbox and execute a calculation based on the input. That is actually a harder task than one might think.
One common solution is to use the Shunting-yard algorithm to parse the expression. See http://en.wikipedia.org/wiki/Shunting-yard_algorithm for more details.
Use NCalc for this kind of job... it is free, comes with source and does all the heavy lifting (parse the mathematical expression etc.) and gives you the result of the calculation.
If you're trying to simply parse out the number from a string, use a function like
Int32.Parse(string)
If you need to take out an EQUATION, like
"3+4/2"
then you'll need to extract each character one at a time and determine what it is.
Like if the string was
"32+4/12"
You'd have to loop through every character in the string, and try to parse the current character into a number.
Theres a function to test if it's a number or not. or just check it's ascii value.
if it succeeds, take the current number plus the next one and try again until you hit a non-number character.
Now you can extract your numbers.
Characters that are not numbers are checked against the mathmatical operators you're allowing. Anything else throws an error.
Once you can extract all the whole equation, you'll probably have to do something like Stack operations to evaluate it. I believe in my Assembly class you'd push a buncha numbers and operators to the stack, and then pop it one at a top from the top, evaluating the previous number with the next number by the operator in between.
I hope this is what you were talking about. Best of luck!