I'm minimalist and I want that my code has as less lines as possible. In every code I write, my goal is to use as much one-lined instructions as possible and avoiding any recurrent code.
Today I'm facing a problem, I'm not able to reduce an instruction even if I'm convinced it's possible.Let's have a look at my instruction :
if((level - 2) >= 0)
{
level -= 2;
}
If know I can use a one-lined affectation in the if like that :
if((level -= 2) >= 0)
But the subtraction while be always applied even if the test is false.
How can I compact this instruction in one line ?
EDIT
I can't use ternary operator because I have to keep the if instruction. Basically I have to execute several operations if the test is true, I just simplified my code to post it.
You could use the ternary operator like this
level -= level - 2 >= 0 ? 2 : 0;
or simpler
level -= level >= 2 ? 2 : 0;
But I don't think that making everything as "short " as possible is the right way to go.
Only subtract when the level is larger or equal to the value you would subtract.
if(level >= 2)
{
level -= 2;
}
Write a general function:
public static bool TryToSubtract(ref int from, int value)
{
bool result = false;
if (from >= value)
{
from -= value;
result = true;
}
return result;
}
and then use that
TryToSubtract(ref level, 2);
You can then even make further statements based on the outcome:
if(TryToSubtract(ref level, 2))
{
Console.WriteLine("Your level was reduced!");
Console.WriteLine("You loser!");
}
If you can live without curlies and newlines, then this could be the shortest, and still very readable (IMHO):
if (level >= 2) level -= 2;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I tried to make a FizzBuzz code in C# but the error code it gives me is that I'm missing a " , " somewhere but I can't find where to place it
Also I know there are other underlying programs in the code I just need this fixed so I can compile and fix them
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
float i = 0;
if (i != 101)
{
i = i + 1;
float i3 = i / 3;
float i5 = i / 5;
float i15 = i / 15;
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
else if ((i3 % 1) > 0)
{
string Hold = ("Buzz");
Print = Hold;
}
else if ((i15 % 1) > 0)
{
string Hold = ("FizzBuzz");
Print = Hold;
}
Console.WriteLine(Print)
; Console.WriteLine("Done");
Console.ReadLine();
}
}
}
}
Fizz-Buzz was originally a game designed to teach children division, it worked like this:
The player designated to go first says the number "1", and each player counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz.
So your program has a number of errors, first one is that you use an if where you should be looping. Your first if statement:
if (i != 101)
{ ... }
Really doesn't do anything. You set i=0 in the previous statement, so i will never equal 101. What you need to do instead is a while loop:
float i = 0.0f;
while (i < 101.0f)
{
//Run the program
}
The next problem you have is that it is OK to use i for an iterator, or even x or y if iterating dimensions, but that is really where the single letter variables should stop. Use meaningful names, it makes things much easier:
So, again we need to check if i is divisible by 3, 5, or both. We can do that with simple boolean variables, no need to make things more complicated.
bool divisibleBy3 = i % 3.0f == 0.0f;
bool divisibleBy5 = i % 5.0f == 0.0f;
The next thing you have wrong is that you have ; in strange places, namely you seem to mix them in on separate lines. Try not to do this. There are very few reasons that a ; should not be on the end of every code line, and there should really only be one per line. So this:
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
Is an error because it treats it all as one line until it hits the ;, so your code really becomes:
string Print = Convert.ToString(i) else;
if (...)
And it should be obvious what the problem with that is.
The last problem I'll touch on really isn't a code issue, but a form one. You have a lot of "holding" variables that don't do anything but temporarily put things in places then put them somewhere else, like this:
if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
What is the purpose of Hold? You could just write:
Print = "Fizz";
The ( and ) are also unnecessary. So lets take all these lessons and put them into the Fizz-Buzz program:
int i = 0; //No reason to use float here, int is just fine
while (i <= 100)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
i += 1;
}
Console.WriteLine("Done");
Console.ReadKey(true);
Or, it can be written with a for loop:
for (int i = 0; i <= 100; i++)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
}
Console.WriteLine("Done");
Console.ReadKey(true);
So you can see how giving variables meaningful names, paying attention to indenting/formatting, and understanding of the ; can help you make debugging easier. Clean, well formatted code is easy to read and debug, and giving variables meaningful names means you can tell what the purpose is without having to read through the entire use of the variable.
Note: Some programmers will argue that Fizz-Buzz can be condensed down to 1-3 lines of code. While it is possible, I would argue that it doesn't demonstrate good programming practices. There is a big difference between readable code that can be maintained, and just making something short for the sake of it being short.
in my project, i need to code for X1 in such a way as
in local variables i declare and wrote the condition as
x1 = 0;
if(in1_w == 1)
{
x1 = 1;
}
if((in1_w == 1) && (in2_w == 1))
{
x1 = 2;
}
i's an microcontroller based in and out so, now i need to know how to right the delay code if x1=1 and x1=2. i have written as
for(k=0;k<=x1;k++)
{
delay_40sec();
}
but don't know how to write separately?
waiting for your kind help plz
You can use
System.Threading.Thread.Sleep(x)
where x is in milliseconds.
However be aware that it is not guaranteed to be accurate nor repeatable.
In C#, if I want to check to make sure that a value does not equal X or Y, I would write something like this:
if(x != 1 && x != 2)
{
//dosomething
}
I want to see if there is a way to write that with OR instead of AND. Something like this (which doesn't work, but its what I am trying to do):
if(x != (1 || 2))
{
//dosomething
}
Obviously that doesn't work because it is trying to evaluate 1 || 2 as its own statement. Does there exist a way to write that correctly?
You can always invert an AND into an OR:
if (!(x == 1 || x == 2))
{
...
}
You have to reverse all the conditions to do it though, as above. The process for doing so is described in De Morgan's Laws (thanks #RichardEverett!).
You could try this one:
if(!(x == 1 || x == 2))
but honestly, I don't see the reason of doing so.
This statement if(x != 1 && x != 2) is far more clear and readable than the above and it does the same.
This (x == 1 || x == 2) evaluates to true if x is either 1 or 2. Hence taking the negation of this, you get that you want.
No, C# doesn't support such a construct presently.
The following is about as close as I could get it, but it's slow!
if (!new[] { 1, 2 }.Contains(x)) { ... }
Note: I'm optimizing because of past experience and due to profiler software's advice. I realize an alternative optimization would be to call GetNeighbors less often, but that is a secondary issue at the moment.
I have a very simple function described below. In general, I call it within a foreach loop. I call that function a lot (about 100,000 times per second). A while back, I coded a variation of this program in Java and was so disgusted by the speed that I ended up replacing several of the for loops which used it with 4 if statements. Loop unrolling seems ugly, but it did make a noticeable difference in application speed. So, I've come up with a few potential optimizations and thought I would ask for opinions on their merit and for suggestions:
Use four if statements and totally ignore the DRY principle. I am confident this will improve performance based on past experience, but it makes me sad. To clarify, the 4 if statements would be pasted anywhere I called getNeighbors() too frequently and would then have the inside of the foreach block pasted within them.
Memoize the results in some mysterious manner.
Add a "neighbors" property to all squares. Generate its contents at initialization.
Use a code generation utility to turn calls to GetNeighbors into if statements as part of compilation.
public static IEnumerable<Square> GetNeighbors(Model m, Square s)
{
int x = s.X;
int y = s.Y;
if (x > 0) yield return m[x - 1, y];
if (y > 0) yield return m[x, y - 1];
if (x < m.Width - 1) yield return m[x + 1, y];
if (y < m.Height - 1) yield return m[x, y + 1];
yield break;
}
//The property of Model used to get elements.
private Square[,] grid;
//...
public Square this[int x, int y]
{
get
{
return grid[x, y];
}
}
Note: 20% of the time spent by the GetNeighbors function is spent on the call to m.get_Item, the other 80% is spent in the method itself.
Brian,
I've run into similar things in my code.
The two things I've found with C# that helped me the most:
First, don't be afraid necessarily of allocations. C# memory allocations are very, very fast, so allocating an array on the fly can often be faster than making an enumerator. However, whether this will help depends a lot on how you're using the results. The only pitfall I see is that, if you return a fixed size array (4), you're going to have to check for edge cases in the routine that's using your results.
Depending on how large your matrix of Squares is in your model, you may be better off doing 1 check up front to see if you're on the edge, and if not, precomputing the full array and returning it. If you're on an edge, you can handle those special cases separately (make a 1 or 2 element array as appropriate). This would put one larger statement in there, but that is often faster in my experience. If the model is large, I would avoid precomputing all of the neighbors. The overhead in the Squares may outweigh the benefits.
In my experience, as well, preallocating and returning vs. using yield makes the JIT more likely to inline your function, which can make a big difference in speed. If you can take advantage of the IEnumerable results and you are not always using every returned element, that is better, but otherwise, precomputing may be faster.
The other thing to consider - I don't know what information is saved in Square in your case, but if hte object is relatively small, and being used in a large matrix and iterated over many, many times, consider making it a struct. I had a routine similar to this (called hundreds of thousands or millions of times in a loop), and changing the class to a struct, in my case, sped up the routine by over 40%. This is assuming you're using .net 3.5sp1, though, as the JIT does many more optimizations on structs in the latest release.
There are other potential pitfalls to switching to struct vs. class, of course, but it can have huge performance impacts.
I'd suggest making an array of Squares (capacity four) and returning that instead. I would be very suspicious about using iterators in a performance-sensitive context. For example:
// could return IEnumerable<Square> still instead if you preferred.
public static Square[] GetNeighbors(Model m, Square s)
{
int x = s.X, y = s.Y, i = 0;
var result = new Square[4];
if (x > 0) result[i++] = m[x - 1, y];
if (y > 0) result[i++] = m[x, y - 1];
if (x < m.Width - 1) result[i++] = m[x + 1, y];
if (y < m.Height - 1) result[i++] = m[x, y + 1];
return result;
}
I wouldn't be surprised if that's much faster.
I'm on a slippery slope, so insert disclaimer here.
I'd go with option 3. Fill in the neighbor references lazily and you've got a kind of memoization.
ANother kind of memoization would be to return an array instead of a lazy IEnumerable, and GetNeighbors becomes a pure function that is trivial to memoize. This amounts roughly to option 3 though.
In any case, but you know this, profile and re-evaluate every step of the way. I am for example unsure about the tradeoff between the lazy IEnumerable or returning an array of results directly. (you avoid some indirections but need an allocation).
Why not make the Square class responsible of returning it's neighbours? Then you have an excellent place to do lazy initialisation without the extra overhead of memoization.
public class Square {
private Model _model;
private int _x;
private int _y;
private Square[] _neightbours;
public Square(Model model, int x, int y) {
_model = model;
_x = x;
_y = y;
_neightbours = null;
}
public Square[] Neighbours {
get {
if (_neightbours == null) {
_neighbours = GetNeighbours();
}
return _neighbours;
}
}
private Square[] GetNeightbours() {
int len = 4;
if (_x == 0) len--;
if (_x == _model.Width - 1) len--;
if (_y == 0) len--;
if (-y == _model.Height -1) len--;
Square [] result = new Square(len);
int i = 0;
if (_x > 0) {
result[i++] = _model[_x - 1,_y];
}
if (_x < _model.Width - 1) {
result[i++] = _model[_x + 1,_y];
}
if (_y > 0) {
result[i++] = _model[_x,_y - 1];
}
if (_y < _model.Height - 1) {
result[i++] = _model[_x,_y + 1];
}
return result;
}
}
Depending on the use of GetNeighbors, maybe some inversion of control could help:
public static void DoOnNeighbors(Model m, Square s, Action<s> action) {
int x = s.X;
int y = s.Y;
if (x > 0) action(m[x - 1, y]);
if (y > 0) action(m[x, y - 1]);
if (x < m.Width - 1) action(m[x + 1, y]);
if (y < m.Height - 1) action(m[x, y + 1]);
}
But I'm not sure, if this has better performance.