Given int x, I want to be able to check if it has increased or decreased by 2. Is there a clean way to do this using the +- condition or should I check both if increased and if decreased separately using or?
Is it possible to make the if statement shorter or do I just have to check multiple conditions at once instead of both at the same time using C#
You can check it using || operator, something like this, here prevX is previous value.
if (x - prevX == 2 || prevX - x == 2) {
}
I would do this by storing initial value of variable and then comparing it with actual using Math.Abs method
var initialX = x; // store value of x before modification
// operations on x
if (Math.Abs(initialX - x) == 2)
{
// x was decreased or increased by 2
}
As long as x is value type, it would be convenient to wrap up operations in separate method and use it like this:
if (Math.Abs(PerformOperations(x) - x) == 2)
{
// x was decreased or increased by 2
}
But PerformOperations can't take params as reference (with ref keyword).
Related
I have number list like below and I should check a condition to get most suitable match.
List<int> numbers= new List<int>();
numbers.Add(1000);
numbers.Add(3000);
numbers.Add(5500);
numbers.Add(7000);
If I send a value to check it should check like below examples
Scenario 1:
If I send a value less than or equal 1000 to check, it should return 1000
Scenario 2:
If I send a value between 1001 - 3000 to check, it should return 3000
Scenario 3:
If I send a value between 3001 - 5500 to check, it should return 5500
Scenario 4:
If I send a value between 5501 - 7000 to check, it should return 7000
Scenario 5:
If I send a value above 7000 to check, it should return nothing.
Can I do this with Linq? or what is the most efficient way to do this?
Update: the numbers in maxCheckPoint is dynamic and it can be any values. So we cannot hard coded and check
You can do this with LINQ:
int input = 1000;
int? result = numbers
.OrderBy(n => n) // get the numbers in ascending order
.SkipWhile(n => n < input) // skip until the remaining set >= input
.Cast<int?>() // cast to nullable int
.FirstOrDefault(); // take the first or default entry (if no items remain, it will be null)
Well, it's too late and my solution is far away from perfect, but:
int number = 400; //imput number
int closest = numbers.Aggregate((x, y) => Math.Abs(x - number) < Math.Abs(y - number) ? x : y); // searching the closer one
int compare;
try{
if (numbers.IndexOf(closest) != 0)
{
compare = Math.Max(closest, numbers[numbers.IndexOf(closest) + 1]); // if it's not 0th and last
}
else
{ compare = closest; // if closest with index 0}
}// check which closest number is bigger
catch{
compare = closest; // if closest is last
}
Console.WriteLine(compare);
If I have a program where x = 2 and I subtracted x by 1, making x = 1. Is there any way to make it so that whenever x will be printed in the program, it will print 1?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x-1);
Console.WriteLine(x); //make x's new value 1
}
}
}
you need to store the calculation to the variable
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);//will print 2
x = x-1; //applying calculation and storing to same variable
Console.WriteLine(x); //make x's new value 1 : Done
}
}
}
You are Displaying the Correct answer.
2 - 1 will Display 1. But u arent changing the Variable or even touching it. You are just using it for a Reference to Calculate what is x - 1?
Displaying only X now will Display 2 as it has NOT been changed.
Setting (Changing the Value of a Variable) is not (normaly) possible inside a Function. There are Functions which take ref params. Which will work with its memory.
You simply need a one-liner.
x = x - 1 translated the value of x is set to the value of x - 1.
it seems much for a simple calculation to require a whole line as it is. But programming will always be one of these things where u have to think literall
This whole problem is a great example for Rubberducking.
think about it literall... line for line what exactly happens and why should it not work?
Write
x--;
Console.WriteLine(x);
That's how you change the value of a variable - you have to assign it a new value.
Alternatively you can write x = x - 1; longhand instead of using the decrement (--) operator.
What you did in your version was to create some output which was the result of x-1, but that doesn't change the original value of x, it just uses x in another calculation.
I've been presented what I think is an ANSI C statement but I don't understand what it is doing or if it is even valid.
x = (y == 4) * 12 + (y == 5) * 24;
Can anyone help me understand what this statement does in terms of C# (which I actually understand).
Thanks
Historically, C did not have a boolean type.* Comparison operators returned either 0 or 1, type int. Any int value (as well as other types) could be interpreted in boolean context, where 0 means false and any other value means true.
C# treats int and bool as completely separate types. The most direct C# equivalent is
x = (y == 4 ? 1 : 0) * 12 + (y == 5 ? 1 : 0) * 24;
Which can of course be improved greatly further.
* Typically, "ANSI C" is intended to refer to the original version of C, even though later versions of C have been adopted by ANSI too. Those later versions do add a boolean type, but the comparison operators still return int values. Similarly, integers in boolean contexts are still allowed as well. They do not change anything relevant to your question.
This is definitely wrong in C#. Both expressions, y==4 and y==5 are evaluated as a boolean. That being said, how can you define the multiplication between a boolean and an integer? This expression is not correct in C#.
I would say that you could try the following:
x = (y == 4 ? 1 : 0) * 12 + (y == 5 ? 1 : 0) * 24;
In the above expression we use the ternary operator, whose logic is quite simple it the expression evaluates to true then return the result after the question mark. Otherwise it returns the value after the :. So if y is equals to 4, then (y == 4 ? 1 : 0) evaluates to 1. Otherwise, it returns 0.
The above solution is based on that hvd mentioned below in his comment, that == returns either 0 or 1 in C.
Is it possible to re-write the following so that it doesn't contain any conditional statements? I'm thinking there might be some clever trick using something like bitwise operations?
int a = // some value
int b = // some other value between 0 and max int
if(b >= 3)
{
return a + 1;
}
else
{
return a;
}
EDIT: to be clear, I'm not looking for a generic way of removing conditionals. I'm looking for a trick to remove the conditionals from this very specific code. Think of it as an academic puzzle.
To give an example, one way to remove conditionals (which happens to yield perf gains in some situations) is to precompute a lookup table and index into that with b instead. In this particular case this is tricky because b could be a very large number. Is there another way?
Here you go
return a - ((2 - b) >> 31);
Explanation:
r = 2 - b, < 0 (i.e. high bit set) for b >= 3
r >> 31, = -1 for b >= 3, 0 otherwise
uint a = // some value
uint b = // some other value between 0 and max int
bool c = b & 0xFFFC
return a + Convert.ToInt32(c);
The fastest will probably be as bitwise operations tend to be very fast
uint a = // some value
uint b = // some other value between 0 and max int
return (b & 0xFFFC) ? a+1 : a;
You could make it better by doing this:
int a = // some value
int b = // some other value between 0 and max int
return (b >= 3) ? (a+1) : a;
?: operator. (but yet it contains conditional statement.)
return b >= 3 ? a + 1 : a;
or
return a + (b >= 3 ? 1 : 0);
Is it possible to re-write the following so that it doesn't contain any conditional statements?
It is not possible to make it work out of no where. you must check this condition any way. There is no magic.
If you want to make your program faster by removing this condition then you picked wrong way. this is micro optimization.
Is there an easy, efficient and correct (i.e. not involving conversions to/from double) way to do floored integer division (like e.g. Python offers) in C#.
In other words, an efficient version of the following, that does not suffer from long/double conversion losses.
(long)(Math.Floor((double) a / b))
or does one have to implement it oneself, like e.g.
static long FlooredIntDiv(long a, long b)
{
if (a < 0)
{
if (b > 0)
return (a - b + 1) / b;
// if (a == long.MinValue && b == -1) // see *) below
// throw new OverflowException();
}
else if (a > 0)
{
if (b < 0)
return (a - b - 1) / b;
}
return a / b;
}
*) Although the C# 4 spec of the Division operator leaves it open whether OverflowException is raised inside unchecked, in reality it does throw (on my system) and the Visual Studio .NET 2003 version even mandated it throw:
If the left operand is the smallest representable int or long value and the right operand is –1, [..] System.OverflowException is always thrown in this situation, regardless of whether the operation occurs in a checked or an unchecked context.
Edit
The crossed out statements about checked and unchecked are all nice and well, but checked is in fact only a compile time concept, so whether my function should wrap around or throw is up to me anyway, regardless of whether code calling the function is inside checked or not.
You can try this:
if (((a < 0) ^ (b < 0)) && (a % b != 0))
{
return (a/b - 1);
}
else
{
return (a/b);
}
Edit (after some discussions in comments below):
Without using if-else, I would go like this:
return (a/b - Convert.ToInt32(((a < 0) ^ (b < 0)) && (a % b != 0)));
Note: Convert.ToIn32(bool value) also needs a jump, see implemention of the method:
return value? Boolean.True: Boolean.False;
Theoretically, it is not possible to calculate the division for a = long.MinValue and b = -1L, since the expected result is a/b = abs(long.MinValue) = long.MaxValue + 1 > long.MaxValue. (Range of long is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.)
The way it works in any sane programming language (one that follows our normal order of operations) is that -1.0/3.0 is equivalent to -(1.0/3.0) which is -0.3333.... So if you want that converted to an int, it's really the cast/floor operator you need to think about, not the division. As such, if you want this behavior, you must use (int)Math.Floor(a/b), or custom code.
You don't need to implement this yourself, the Math class provides a builtin method for doing Euclidean division: Math.DivRem()
The only downside is that you have to provide an assignable variable for the remainder:
long remainder;
long quotient = Math.DivRem(a, b, out remainder);