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);
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.
Which do you think is better..
if (thing.GetType() == typeof(thisthing))
{
//do stuff for this type of thing.
}
Or give the objects an Enum property
if (thing.TypeName == NamesEnum.thisthing)
{
//do stuff for this type of thing.
}
Neither of these is a particularly extensible or maintainable approach.
It's typically better to design this directly into a virtual method in your type hierarchy, and just call the method. This allows other classes to override and provide custom functionality as appropriate.
In your case, the thisthing type (which should be named ThisThing if you want to follow .NET naming conventions) would just have a DoStuff method which could be virtual if needed, and call it.
It depends:
if (thing.TypeName == NamesEnum.thisthing)
will run more performant then GetType() as, this a simple comparison of 2 numeric values.
But:
if (thing.GetType() == typeof(thisthing))
is more more "flexible": when you do some refactoring, change type name or whatever, this condition will still work.
But will fail in condition, if 2 types belong to 2 different assemblies, instead in first case this still will be matched as equal,as you campare not types but just enum values.
In short, there is no best approach, just most suitable for your needs.
IF you are working with basic types that don't have sub types...
your first example can be shortened nicely to
if (thing is typeof(thisthing))
Depends on the situation really. If you get to a lot of different types you're going to want a switch statement at some point, so I would say option 2 if there are going to be a lot of types.
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.
My question relates to performance comparison (numeric estimates) pertinent to the following sample cases implementing for-loop in C# 4.0 and/or C# 5.0 in 4 different manners:
for (int i=0; i<10000; i++;){string _s="a";}
for (int i=0; i<10000; ++i;){string _s="a";}
for (int i=10000; i>0; i--;){string _s="a";}
for (int i=10000; i>; --i;){string _s="a";}
Question: Which of the following implementations will provide better performance (execution time) in generic for-loop implemented in C# 4.0 or C# 5.0?
Note 1: string _s="a"; is just a sample operation, potentially could be omitted for testing purpose.
Note 2: so far, as per discussion on (Is there a performance difference between i++ and ++i in C?) it seems like ++i runs faster than I++ in C++.
The optimizer should know that the pre-incremented value of i is never used, and therefore they should be the same (simply increment i).
The only reason i++ may be slower than ++i is if the compiler has to save off the old, pre-incremented value before incrementing i. However, given low register pressure, this should be as trivial as one additional "move" instruction.
If you really care, I would suggest you benchmark your test cases. Stopwatch provides enough functionality to get a pretty good estimation.
Also, looking at the generated IL will show you if there is any difference at all.
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.
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.
Could this code snippet
StringBuilder builder = new StringBuilder();
builder.Append("Have a ");
builder.Append("nice day!");
be better written like this?
StringBuilder builder = new StringBuilder();
builder.Append("Have a ")
.Append("nice day!");
In C# and Java, what would a better way to write it be?
The pattern in the 2nd example is a "fluent API" / "fluent interface"; frankly neither is strictly better - but if the second exists it can be slightly inefficient not to use it. In .NET IL terms, the first syntax involves an extra ldloc and pop per iteration, which the second avoids - but that is rarely hugely significant. Either will work fine.
Personally, I would optimize for readability and convenience unless you know it is in a performance-critical spot.
Indeed, you could just use:
string s = "Have a " + "nice day!";
which the compiler (in C#, at least - I don't know about java) will compute at compile-time (since they are both constants) and compile down to a single ldstr (which is automatically interned, too).
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.
What is the optimal amount of lines in method shold be used?
Curly braces doesn't count.
What code is better? Code is runing in Main()
//1st
string line;
while ((line = Console.ReadLine()).ToLower() != Break)
{
commandAnalyzer.AnalyzeAndRun(line);
}
// or 2nd
RunTextualInterface(commandAnalyzer);
private static void RunTextualInterface(TextCommandAnalyzer commandAnalyzer)
{
while (notBreakCommand())
{
analyzeCommandWithHelpOf(commandAnalyzer);
}
}
private static void analyzeCommandWithHelpOf(TextCommandAnalyzer commandAnalyzer)
{
commandAnalyzer.AnalyzeAndRun(readNewLine());
}
private static bool notBreakCommand()
{
return readNewLine() != Break;
}
private static string readNewLine()
{
return Console.ReadLine().ToLower();
}
// result just the same
P.S I am asking cause out teacher said that every method must have maximum 6 lines.(Curly braces dosn't count)
I think first approach would be better in this case. Too many method will decrease the readability when the logic involved is not too complex and not that large that it should be a separate method. Also it will make sense to make different methods if this logic has to be used by other parts of program as well. But again as the methods are so small, it doesn't even makes sense to me to make a separate method in this case
You want to reduce the amount of code you need to maintain without reducing readability. I like your first answer. Read Steve Yegge on how code size is Code's Worst Enemy.
Strive to keep everything the reader of your code will need to understand your code as local as possible. Use abstractions (e.g. refactoring stuff to methods) where they help. Avoid abstractions (e.g. inventing new names for operations your reader is already familiar with) where they don't help.
As to the various rules on method sizes: They aren't rules. They are guidelines. Whenever your method gets too long, stop. It could be a sign of a bad design. But it doesn't have to be - use the rule to trigger a closer look at your code.
Develop a sense of style. This will change all the time as you progress. Don't be afraid to update your style all the time - though do try to keep the same style during a project. Try out different styles and gain experience. It is the only true path.
If you're interested in that kinda questions, I'd suggest reading:
Code Complete 2nd Edition
The book has a chapter about that:
"Creating high quality code" -> "How long can a routine be?"