C# Programming Best Practices For Mathematical Calculations [closed] - c#

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.
Can anyone let me know where can I read the best practices to write an application that relies heavily on mathematical calculations? For example, suppose I was asked to write a C# application that generates 100 even numbers. I would write the following:
public void GenerateEven() {
for (int i=0;i<100;i++) {
Console.WriteLine(i * 2);
}
}
However that is not the best practice to do. The best way to generate even number would be, for example:
public void GenerateEven() {
int i=0;
while (i <200) {
if (i % 2 == 0) {
Console.Writeline(i);
}
}
}

If you're after expressiveness, take a page from functional programming:
public static IEnumerable<int> EvenNumbers(int start = 0)
{
while (true)
{
yield return start;
start += 2;
}
}
Then to get your sequence:
var firstHundredEvenNumbers = EvenNumers().Take(100);
It really depends upon your goal. If you're looking for composition, the above is great. If you're looking for raw speed, then you should mash all the logic into one ball and tune the heck out of it -- but it'll be harder to work with.

What makes you think the second method is the best way to do it? If I were asked to do that problem, then I would do this, so I only loop 100 times.
for (int i = 0; i < 200; i += 2)
Console.WriteLine(i);
As for your more general question, there is no one document or book that gives you best practices on how you should form loops or approach mathematical problems. This is where a computer science education comes in handy to analyze your problem and try to find an optimal solution.
In your sample problem each one of the solutions proposed (including the ones proposed by me) come down to a big O of N, so the computational differences between these solutions are negligible. The growth is linear with respect to N. The only advantage my solution provides is that it only loops over the necessary items to generate the output, instead of skipping items that do not meet the criteria.

Actually you may be looking for The Art of Computer Programming by Donald Knuth
Its called the bible of all fundamental algorithms and contains many kinds of programming algorithms and their analysis. But it does not cover any language specific moments.

If you want to generate numbers, you can use Enumerable.Range thus:
Edit: (rotem)
var a = Enumerable.Range(1,100/ 2+ 1).Select((X) => X * 2).ToList();

Related

Why doesn't C# allow an else clause on loops? [closed]

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.

Logic to write the first 10 numbers without using any for loop [closed]

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 am fresher and just gave my first interview on friday.
In a machine test they ask me to write a program to add first ten numbers i.e 1-10 without using any for loop. I tried it alot but can not find the solution. How can we write a program logic to get the sum of first 10 natural numbers without using for loop.
if they asked you not to use for loop , then you could have use while or do while.
There is another way to do it if you dont want to use any knd of loop.You can use the formula
1+2+3+.........+(n-1)+n=(n*(n+1))/2 .
you had to add first 10 numbers so you could have use it like
(10*(10+1))/2.
Console.WriteLine("{0}",(10*(10+1))/2);
You can make it more general by asking the user the value of n etc.I hope this will help you.
If I understand what you're saying correctly, you could just use simple mathematics.
x = firstnaturalnumber;
You want to have:
(x + 0) + (x + 1) + (x + 2) ... (x + 9)
Natural numbers are whole integers, which makes this mathematically sound. The final equation is:
sum = 10x + 45
The natural numbers are a special case of an arithmetic series. The sum of any arithmetic series can be computed with a simple formula, without requiring a loop.
S = (n / 2) * (a1 + an)
Personally, I think it would kind of unfair for an interviewer to expect you to just remember this formula off the top of your head. However, you probably would impress an interviewer a great deal by working through the series and figuring out the formula yourself!
if they specified not to use 'for' loop then there are other loops available such as do-while or while. Recursive function is also a good choice.
Actually, they have already specified the numbers to be added. So, instead of being a smart arse, use '+' to add them directly. Yeah I one it is dumb answer but it is an answer.
static void Main(string[] args) {
Console.WriteLine("{0}", SumRecursive(1,10));
}
static int SumRecursive(int min, int max) {
return _SumRecursive(min, max);
}
static int _SumRecursive(int min, int val) {
if (val == min)
return val;
return val + _SumRecursive(min, val - 1);
}
You can achieve it with a recursive method , and there is no for loop either
public int AddDown(int i)
{
return i += (i >= 1 ? AddDown(--i) : 0);
}
x= 1 + 2 + 3+.....+n-2 +n-1+n
x =n +n-1+ n-2+ ....3+2 +1 just reversing
sum up both sides
2x= (n+1) +(n+1) +(n+1)+ .....+(n+1) ///n times
2x= n(n+1)
x= n(n+1)/2
so in your case x= 10(10+1)/2 = 55

Order of Operations Simple Brain Teaser [closed]

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);

Method lines amount. Clean code [closed]

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?"

Piece of code that can kill computer performance [closed]

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'm searching for code in c# that can kill computer performance (CPU performance, maybe cpu - memory link performance too) as much as it is possible (it will run on 4 core box so I'm going to create 4 threads and run it simultaneously).
Should it work on int / double / numeric data type / should it have some crazy data structures (but it should not take too much memory) .
Do you have any suggestions ?
Calculate PI using all processors.
You could use parallel Linq to generate a Mandelbrot (Jon Skeet has the code readily available).
Have a program that writes copies of its executable to the drive multiple times for each thread. Have each of these copies of the program then triggered by the program. :)
If you want to kill a machine's performance, try hitting the disk, because IO interrupts tend to affect everything even on a good CPU scheduler. Something like enumerating a directory of many little files, or writing a lot of big files to disk would do the trick.
Why re-invent the wheel? Use existing Load Testing software.
Calculate a long sequence of prime numbers. The following link contains code that can be modified to do this..
Program to find prime numbers
Call Bitmap.GetPixel, in a loop, in an image processing application.
I would say: a naieve (brute force) travelling salesman implementation:
(from wikipedia):
The Travelling Salesman Problem (TSP) is an NP-hard problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once.
Brute force solving of N Queens (see wikipedia) for for example 64 queens.
Because a simple loop like this can be optimized away (sometimes only after a few minutes already running):
while(true) {
i++;
}
You can, as well, resolve a very long encrypted message, encrypted by a key such as 2048 bits.
That's a killer.
An open-source, multithreaded 3D modeling program rendering an extremely complex lighted scene will pound the strongest system into submission.
Okay, how about some infinite recursion in the spirit of StackOverflow?
void deathToAllRobots(int someMeaninglessValue) {
deathToAllRobots(someMeaninglessValue+1);
}
int *x;
while(1)
{
x = new int[10];
}

Categories