As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm trying to solve various puzzles of recursion and one problem I came across is Equation Generator. I'm unable to understand how to solve this problem. The problem statement is like this.
You are given a 4-digit number. For example, 1234. Now, you've got to
make an equation out of it, by placing arithmetic operators and an
equal-to sign in between the digits without changing order of the numbers.
1=2+3-4
1-2=3-4
12=3*4
12/3=4
1^2+3=4
I would like to write a function that generates first equation that it can find and return it in C# or Java. Can any one give a clue or pointer as to how to solve this problem recursively?
Can any one give a clue or pointer as to how to solve this problem?
Yes. In addition to all the other good suggestions here: Read "How To Solve It" by Pólya. The book is about how to solve math problems but much of the advice in there is applicable to programming problems.
http://en.wikipedia.org/wiki/How_to_Solve_It
The suggestion of Pólya's that best applies to your problem is solve a simpler problem. For example, can you solve this problem?
You are given a 4-digit number. For example, 1234. Now, you've got to make an equation out of it, by placing an equal-to sign in between the digits without changing order of the numbers. For example:
1=234
12=34
123=4
Of course all of those equations are false, but clearly if you cannot solve the problem of generating false equations with no operators then you cannot solve the harder problem of generating true equations with operators. Solve the easier problem, and that will give you insights into how to solve the larger problem.
Split the task into three different subtasks:
Generate all combinations of operators (seems that the numbers are always in the same order. Consider = as an operator)
Evaluate a single combination of operators to determine whether true or false
Filter all combinations using the evaluation
See this for generating combinations.
Finally, after you also have an evaluation function...
var results = GetCombinations().Where(comb => Evaluate(nums, comb)).ToList();
Note to all that I'm intentionally brief in order to avoid spoon-feeding.
Hint: You could:
generate strings and then attempt to parse and evaluate them as equations to see if they are syntactically valid and "true", or
generate and evaluate equation trees, evaluate them and then unparse them to Strings if they are "true".
Either approach has challenges ... but discovering and solving them is your job :-)
My old math teacher used to play this game with the date everyday. Funny.
Anyway, the key is to step through every possible equation sequentially. (I know it's a recursive problem but hear me out)
Something like this:
recursivefunction(sequence):
if valid sequence return
foreach operator position
foreach operator
recursivefunction(sequence with new operator)
Some hints for you:
Enumerate all equations. After this step, you will get "1+2=3+4","1=2+3-4","1+2-3^4" etc.
Delete all of invalid equations. After this step, you will get "1+2=3+4","1=2+3-4" etc.
Evaluating all valid equations and see it's equals or not. After this step, you will get "1=2+3-4" etc.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I decided to learn some Python (IronPython) syntax today. In doing so, I was impressed by a construct that it allows with its loops.
Python supports an else clause on its loops. An else on a loop basically says, "if this loop finished normally, then enter this clause".
Allow me to demonstrate using C#.
This code:
Something something = SomeCallToSetThisUp();
bool isCompatable = false;
foreach (Widget widget in widgets)
{
isCompatable = widget.IsCompatableWithSomething(something);
if (!isCompatable)
break;
}
if (isCompatable)
compatableSomethings.Add(something);
could become this code (not valid C#):
Something something = SomeCallToSetThisUp();
foreach (Widget widget in widgets)
{
if (!widget.IsCompatableWithSomething(something));
break;
}
else
compatableSomethings.Add(something);
Having never seen this, it struck me as cool. And once you learn it, it seemed as readable as any code I have seen.
While not universally needed (sometimes you want to affect every item in the list), I do think that it would be useful.
So, my question is: Why isn't this in C#?
I have a few ideas why:
break can make debugging harder, so the designers did not want to encourage it.
Not everything that is shiny can make it into the language. (limited scope).
But those are just guesses. I am asking for an actual canonical reason.
The usual answer is because no-one asked for it or the cost of developing and maintaining it outweights the benefits.
From Eric Lippert's blog:
I've already linked several times to Eric Gunnerson's great post on
the C# design process. The two most important points in Eric's post
are: (1) this is not a subtractive process; we don't start with C++ or
Java or Haskell and then decide whether to leave some feature of them
out. And (2) just being a good feature is not enough. Features have to
be so compelling that they are worth the enormous dollar costs of
designing, implementing, testing, documenting and shipping the
feature. They have to be worth the cost of complicating the language
and making it more difficult to design other features in the future.
After we finished the last-minute minor redesigns of various parts of
C# 3.0, we made a list of every feature we could think of that could
possibly go into a future version of C#. We spent many, many hours
going through each feature on that list, trying to "bucket" it. Each
feature got put into a unique bucket. The buckets were labelled:
Pri 1: Must have in the next version
Pri 2: Should have in the next version
Pri 3: Nice to have in the next version
Pri 4: Likely requires deep study for many years before we can do it
Pri 5: Bad idea
Obviously we immediately stopped considering the fours and fives in
the context of the next version. We then added up the costs of the
features in the first three buckets, compared them against the design,
implementation, testing and documenting resources we had available.
The costs were massively higher than the resources available, so we
cut everything in bucket 2 and 3, and about half of what was in bucket
1. Turns out that some of those "must haves" were actually "should haves".
Understanding this bucketing process will help when I talk about some
of the features suggested in that long forum topic. Many of the
features suggested were perfectly good, but fell into bucket 3. They
didn't make up the 100 point deficit, they just weren't compelling
enough.
http://blogs.msdn.com/b/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx
Additionally, you need to weight if the feature will be easily understood by existing / new developers. IMHO else on loop is not very readable, especially since the keyword for 'execute this block if the previous one finished OK' is finally.
What is more, I think Enumerable.Any / Enumerable.All methods are much better in this scenarios.
Looping through a collection and checking a condition are different things, so they should be separate language constructs.
Because for else loops are a hack from languages like python. If you feel like you need a for else loop, you should probably put that code in a separate function.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a simple piece of code that doesn't do what I expect. What is wrong with this code?
int value1 = (int).5*100;
This is pretty easy but through me for a loop for a good moment. Of course, the answer is trivial and already known. But, I thought it might be fun for someone to think about.
Credit will be given to first person who come up with the correct solution and explains why.
"what is wrong": the insufficient use of parenthesis, forcing me to memorise and recite stupid precedence rules (which are intended to satisfy compilers, not human eyes), making it hard to write and even harder to maintain.
If the meaning is even a little bit in doubt, add parenthesis. Even if they aren't needed. Then this is a non-issue. And you don't have to memorise anything!
If the code was written as either:
((int)0.5)*100
or:
(int)(0.5*100)
Then I doubt the question would ever be necessary :)
Firsty it casts .5 to int, which results in 0, then it multiplies it by 100 which results in ( 0 * 100 ) 0.
If you expect it to be 50 then you need to use parenthesis (so multiplication goes first, then type cast):
int value1 = (int)(.5*100);
It is always better to put more parenthesis than less, it costs nothing and it increases readability and understanding.
MSDN Library: Operator precedence and associativity.
It has to do with the precedence of the cast, the cast has an higher precedence so i gets executed before the multiplication operation, you have to use parenthesis to alter the precedence, try in this way :
int value1 = (int)(.5 * 100);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Evaluate C# string with math operators
So lets say I have a basic string with the value "1*2+4"
How would I go about parsing the information and then doing the calculation?
I am self teaching c# but my assumption is this is a common issue in programming but without using a library how would one do this?
My results so far have got me splitting the string up and putting them into an array of chars, but this is where I've stopped since I am trying to figure out how to compare chars to operators and chars to ints.
I am not sure if I am going the right way about this but would be great if someone could point me in the right direction.
Thank you for your help in advanced.
What you're looking for is the Shunting-yard algorithm.
You'll need at least two stacks; one for storing operators and one for operands. After you fill the stacks you can make a RPN and calculate the answer.
Well c# (or any other language) might provide you with various tools to help you, but the overall approach to the problem will always remain the same whatever the programming language be.
So yes, you do split up into operators & integers. You do recognize the characters one by one, but try to do it in the most efficient way of the language. Fosco's anser points to the right link. Use Ncalc Library than doing manual labor.
However, to complete what you started :
int.Parse(str)
int.TryParse(str, out num)
...are the functions you may consider to convert character strings into integers (which you got, by using split() function?) in C#. You can read about them here...(Parse, TryParse)
If you want to learn how the various existing libraries do it, you should learn about parsing, lexical and syntactic analysis, expression trees, compiler theory, etc. Also, go through the source-code of any of the multiple open-source libraries that do it.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've just read this page http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
One of the things they did was to convert the arabic date to the arabic calendar. I'm wondering if it is a good idea at all to do so. Will it actually be annoying/confusing for the user (even if the user is Arabic).
Also, my second question is that do we really need to change 3,899.99 to 3.899,99 for some cultures like German? I mean it doesn't hurt to do so since the library already does it for us but wouldn't this actually cause more confusion to the user (even if he is German).
I'm sure whatever culture these people come from, if i give you a number 3,899.99 there's no way you'd get that wrong right? (since he'd probably learned the universal format anyway)
Your problem here seems to be a bad assumption. There is no "universal format" for numbers. 3,899.99 is valid in some places, and confusing in others. Same for the converse. People can often figure out what they need to (especially if it's in software that is clearly doing a shoddy job of localization otherwise. :) ), but that's not the point.
Except in certain scientific and technical domains that general software doesn't usually address, there's no universal format for any of these things. If you want your software to be accepted on native terms anywhere but your own place, you'll need to work for it.
To me it seems like it would be much less confusing to see dates and numbers in the format you're used to (in your country or language) - why do you think it would be the other way around?
The point of localization is to make your application look more natural for the user. It is definitely advisable to do this in your application if you use it internationally. While you can use US standards, that is not very customer-friendly way of doing things.
How would it be more confusing to a person to see the format they are familiar with? Meet people where they are with your application. If their standard is 10.000,00 and you are showing them 10,000.00, even if they understand it, it does make it a bit disconcerting. Reverse the situation and think what you would like. Would you like a developer using 10.000,00 for their application because you can understand it just fine?
Depends. 3.899,99 to me looks like two numbers. 3.899 and 99. I imagine our number formatting looks similarly funny to foreigners. Sure, I could guess what it means here, but what if you had a whole bunch of numbers like this clustered together? The winning lotto numbers are 45,26,21,56,94,13. Is that one big number, or 6 2-digit numbers?
Date formatting is especially important. 01/02/03. Is that Jan 2 2003, Feb 1 2003, Feb 3 2001 or what? Different cultures specify the d/m/y in different orders. Also, when spelled out, they obviously have different names for the months.
If you have the time and resources to internationalize it, I think you should.
As a foreigner myself, I can assure you that localization helps a lot in terms of user satisfaction. Commas or dots in numbers may induce big mistakes. Another on is the relative position of days and months.
To improve even further, create translations and add an option to choose locale. That way you will have close to 100% customer satisfaction
another important thing is input. if you don't have localization, take the user input "1.234"... what does the user mean? 1.234 or 1234 ? ... there may be users that don't like their values to be off by factor 1000 ... who knows? ;)
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Here is an example of the type of article I'm talking about:
http://support.microsoft.com/kb/319401
I assume these articles are written by people who work for Microsoft and that the code in the articles will always be rock solid and never contain any malicious code. I just want to make sure I can explain to my boss that this is an ok place to copy code from (I've been told never to copy code from the internet, but this seems like a safe source).
I would trust them not to be malicious, but they're not always good code. (MSDN samples are sometimes pretty awful.)
For example, here's some code in the sample you gave:
compareResult = ObjectCompare.Compare
(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
Now, there are two issues here:
Why is it deemed valid to have a comparer with no sort order? This should be a constructor parameter, validated at the point of construction IMO.
You should not just negate the result of one comparison to perform a "reverse comparison". That breaks if the result of the first comparison is int.MinValue - because -int.MinValue == int.MinValue. It's better to reverse the arguments used to perform the original comparison.
There are other things I'd take issue with in this code, but these two should be enough to make my point.
I heartily agree with the other answers too, in terms of:
- Check the copyright / licence etc of any code you want to use
- Make sure you understand anything you want to use
Your boss probably wouldn't mind if you only copied the code into a test project that you use to test and understand the code. You can then use what you've learned to write the production code.
And while I don't think anyone outside of Microsoft knows the names of the people who write those support articles, they come from the same vendor that your toolchain does, so if you don't trust the support articles, then you can't trust the tools you've bought either.
Microsoft Knowledgebase articles show safe (as in non-malicious but not necessarily secure) code, but usually the example provides the most basic use case possible. There's a good chance that you'll have to tweak the code a bit for it to work the way you want.
You should also pay attention to the date of the articles. For example, the article you link to is almost three years old. There's definitely a better way to handle that situation now.
Be aware that most codes in articles are there to help you understand the concepts. They are not "production ready". Learn the concepts instead and implement your own.
Have you been told not to copy code from the internet because of rights issues? If so then you don't have to worry about this Microsoft code.
I would advise you not to use any code you don't understand. If you can't say if the code is malicious or not don't use it.
MSDN and kb support articles are written by MS employees that are part of the given product's UX team (user experience). These are people who typically have a background in technical writing, but are not necessarily developers themselves (although some are). It's very common for the UX team to collaborate with developers on the product to ensure their code samples are correct. However this collaboration in my experience is one of the lowest priorities a typical MS developer has and can go ignored, and so it can at times lead to poor code getting out.
With that said, I completely agree with Carl Norum's comment. Copying code you do not understand is done at your own risk. Make sure you understand any code you place in your product!
I've always found the Microsoft articles to be of the highest quality (sadly not their products).
However, there's always the danger of a spoofing site.
Explain that you carefully read the article to understand the information in there, and only copy code that you understand.
If you don't understand the code, then even if the code is correct it may not be doing what you actually need done, thus your program will be incorrect.
You also will have a hard time debugging and maintaining code if there are parts that you don't understand.