C# Using Enumerable.Range() - c#

Am I using this is the correct manner? As far as I understand it, the following check should be false:
int myVal = 37;
if (Enumerable.Range(0, 10).Contains(myVal))
// Do something
else if (Enumerable.Range(11, 33).Contains(myVal))
// Do somethiong else
But I seem to be getting some cases where //Do somethiong else is executed. Can I not use Enumerable.Range is this way?

The signature for Enumerable.Range provides a clue:
public static IEnumerable<int> Range(
int start,
int count
)
The first parameter is called start; the second is called count. So your second call is returning 33 values starting with 11, which will include 37.

If this particular example, its inefficient to create an enumerate in this fashion simply to check that a value lies within a particular range. if (x < y) is probably better.

It will result in every value being checked, and is a little confusing, why not do:
int myVal = 37;
if (myVal >= 0 && myVal <= 10)
// Do something
else if (myVal <= 33)
// Do somethiong else

Related

How to check if a number exists in a specified digit of an integer ( C# )

I want to generally verify if a number/character exists within a specified index of an int value.
Here is pseudocode of what I want
if (octet[1].Exists){
return true;
} else {
return false;
}
// receiving int octet = 103 will return true.
// receiving int octet = 7 will return false.
Is there a function that already does this, or do you have to make one on your own?
Convert to a string then check the length?
var str = octet.ToString();
return str.Length >= 1;
I don't know a function like this, but you can write your own.
In instance:
var func = (int octet, int index) => (octet / (int)(Math.Pow(10, index)) != 0);
I would suggest using a System.Linq binding for this. Here is an example:
octet.ToString().Contains(n);
Where n is the digit you're looking for in string or char form. Hope this helps!
Just parse the int to a string and check if the number you are looking is equal to expected position.
var number = 12345;
if(number.ToString().IndexOf('2') == 1)//check if the value 2 is on the second position of the array
{
Console.WriteLine("yes");
}

What is the appropriate way to append string to the end of the current line?

I'm working through a practice problem for one of my classes and I'm having a bit of trouble with part of the prompt.
We need to:
Write code to go through number -20 - 20 (but skip 5-15 inclusively)
If the number is negative, the line should start with an "*"
If the number is divisible by 2, add "#" to the end of the current line
If the number is divisible by 3, add "!" to the front of the line
If the previous line has both "!" and "#", then add "wow" to the end of the current line (Hint: use bool)
With the code I've written so far, I've managed to complete the first two tasks on the list, but I run into trouble starting with the third task. In my code I'm using
if (num%2==0)
{
Console.WriteLine(num+"#");
}
but all it's doing is outputting another number with "#" instead of putting "#" on the current line. How do I make it so "#" is appended to the end of the current line?
Here's my code for reference:
static void Main(string[] args)
{
int num = -20;
while (num <= 20)
{
if (num < 5 || num > 15)
{
if (num < 0)
{
Console.WriteLine("*" + num);
}
if (num%2==0)
{
Console.WriteLine(num+"#");
}
else
{
Console.WriteLine(num);
}
}
num++;
}
}
Since we are only working with the first 3 points in this question (try the other 2 yourself), I will only address those.
The main problem with the code is that it will always write the number more than once if more than one rule applies to it. There's 2 ways to tackle this. Also note I cleaned up the code a bit and I'll explain why later since it's secondary.
Fix
Method 1 : Incremental Writing
This method uses incremental writing to apply rules and then write a new line at the end before going to the next iteration.
// More succinct than a while loop for this particular scenario
for (int num = -20; num <=20; num++)
{
//Skip while avoiding nested if
if (num >= 5 && num <= 15)
continue;
//Since it needs to start with * in this case we prioritize it
if (num < 0)
Console.Write("*");
Console.Write(num);
// Since this would need to be appended at the end if it's true
if (num % 2 == 0)
Console.Write("#");
Console.Write(Environment.NewLine);
}
Method 2: Store the line then print before next iteration
In this case you would build the line that you want to print and then use one Console.WriteLine statement to write it while avoiding duplication. The writing would need to be done before moving to the next iteration.
You can use string concatenation instead of StringBuilder which would generally be more costly but in this case performance doesn't really matter (string are really small and amount of concatenation is minimal). However this would be a typical use case for a StringBuilder.
Also, since we know we know that we will always print out num when we aren't skipping then we can start off with num. But we could also do it like Method 1 where we add it in the middle. I'll illustrate both ways.
StringBuilder constructor with number
// More succinct than a while loop for this particular scenario
for (int num = -20; num <= 20; num++)
{
//Skip while avoiding nested if
if (num >= 5 && num <= 15)
continue;
// Create and update your string in a string builder, apply rules thereafter
// (this constructor usage means we don't need to add the number later)
var line = new StringBuilder(num.ToString());
//Since it needs to start with * in this case we prioritize it
if (num < 0)
line.Insert(0, "*");
// No need to add the number, already present
// Since this would need to be appended at the end if it's true
if (num % 2 == 0)
line.Append("#");
Console.WriteLine(line.ToString());
}
StringBuilder constructor without number
// More succinct than a while loop for this particular scenario
for (int num = -20; num <= 20; num++)
{
//Skip while avoiding nested if
if (num >= 5 && num <= 15)
continue;
// Create and update your string in a string builder, apply rules thereafter
// (this constructor usage means we must add the number later)
var line = new StringBuilder();
//Since it needs to start with * in this case we prioritize it
if (num < 0)
line.Append("*"); // NOTICE: This is now Append instead of Insert since line is empty
// Since we didn't add the number before
line.Append(num);
// Since this would need to be appended at the end if it's true
if (num % 2 == 0)
line.Append("#");
Console.WriteLine(line.ToString());
}
Additional Changes
for loop is better suited for this situation since you have an int with a clear start, end and an incrementor supported by the structure.
Avoid unnecessary nesting of conditions, common newbie mistake. If you have a condition to skip in certain cases, simply check and skip and otherwise the rest of the code will apply. This could otherwise lead to really annoying duplication and condition checks that are unnecessary (most of the time).
use string.concat but first save the string into variable and reach the end and finally do the concatenation

How to update variable from with if statement MQL5

I have been googling for two days now, but can't figure this out and it seems to be basic.
Within the void OnTick(), I would like to create a variable int a;. Lets say it starts out with no value int a;, then I test condition if a is NULL or || equals 1 like this if (a == NULL || a == 1) which should always return true the first time the if statement runs due to NULL. I then assign a value to the variable a = 0;, so now a should equal 0.
This should trigger the else if(a == 0) the next time OnTick() is called, at this point I assign a = 1; resulting in the if being triggered next time round, etc and infinitum, constantly checking and assigning values switching between 0 and 1.
void OnTick()
int a;
if (PositionsTotal() < 1)
{
if(a == NULL || a == 1)
{
a = 0;
}
else if(a == 0)
{
a = 1;
}
}
I do not know what is going on, but during Testing in Strategy tester, I am getting a long string of numbers which switches between negatives and positives always with the same number -123456789 or 123456789, always 9 digits long.
Or during Debugging from Meta Editor. A random positive 3 digit number which never changes!
So far I have had both 303 and 597.
Beyond frustrating and most likely answered somewhere else.
Just not sure how to phrase the search term.
Thanks for you help.
I think the problem is that you declare your variable a inside the method OnTick, so it starts with an arbitrary value every time you call this method. Try declaring it outside this method.

C# Finding the index of a number in an array using recursion

So in the programming course I'm taking we learned about recursion. I got an assignment to write recursive function that gets sorted array and a number and return the index of that number in the array if existed.
I didn't quite understand yet the subject of recursion so I need a little help with my code. I think i'm at the right direction but again, I'm a little struggling with the subject so I thought I could find guidance and help here.
this is the code I have at the moment:
private static int arrayIndexValue(int[] arr, int ind)
{
if (ind > arr.Length/2)
{
return arrayIndexValue(arr.Length/2, ind)
}
else if (ind < arr.Length/2)
{
return arrayIndexValue(arr.Length/2)
}
}
basically what i wanted to write here is something like this:
if the number the user inserts is smaller then the middle of the array, continue with the function but with the array cut in half (Binary search)
same if the number is bigger (i suggested to use my function with something like the binary search but as you can see i dont quite know how to apply it to my code)
Recursion works by breaking the entire problem into smaller parts. If you are at the smallest part (meaning that your array has only one value) then you would have your solution. This would also be your first case that you have to handle.
if (arr.Length == 1) return arr[0];
Now you can start to break down the problem. Binary left or right decision. As you already wrote you want to check weather the number is left or right from the middle of your array. So in your condition you need to access the element in the array using the [ ] operator:
if (ind > arr[arr.Length / 2]) // check if larger than the middle element
To extract a part of the array you need a second array in which you can copy the content that you want. Since you intend to pass only half of the current array into the recursive call you also need only half of the size.
int [] temp = new int[arr.Length / 2];
Now you can copy the part that you desire (first or second) depending on your condition and keep searching with a recursive call.
To copy the Array you can use the Arra.Copy method. You can pass the start and length to this method and it will copy the left or the right part into the int [] temp array. Here is an example of how to copy the right part:
Array.Copy(arr, arr.Length / 2, temp, 0, arr.Length / 2);
In the end you will need to fire your recursive call. This call will expect the new array and still the same number to look for. So since you copied either the left or right half of the previous array, now you pass the new short array to the recursive call:
return arrayIndexValue(temp, ind);
And there you have it
i got an assignment to write recursive function that gets sorted array
and a number and return the index of that number in the array if
existed.
In your method you check indexes, not values - you should compare values of elements, not indexes.
To write recursive function to find element you should pass array, element to find, start index and end index. Start index and end index will be used for finding in part of array.
Your method will be something like this:
private static int GetIndex(int[] arr, int element, int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
return -1; //not found
}
var middleIndex = (startIndex + endIndex) / 2;
if (element == arr[middleIndex])
{
return middleIndex;
}
if (element < arr[middleIndex])
{
return GetIndex(arr, element, startIndex, middleIndex - 1);
}
else
{
return GetIndex(arr, element, middleIndex + 1, endIndex);
}
}
and to get some index:
static void Main(String[] args)
{
var arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var element = 5;
var index = GetIndex(arr, element , 0, arr.Length - 1);
}
So the problem you have right now is that you haven't broken your problem into repeating steps. It actually should be very similar flow to a loop without all the variables. I want to do something a little simpler first.
void int find(int[] values, int at, int value) {
if (values.Length >= at || at < 0) {
return -1;
} else if (values[at] == value) {
return at;
}
return find(values, at+1, value);
}
This function just moves a index up one every time via recursion, but we can also do something very similar with a loop.
void int find(int[] values, int at, int value) {
while (values.Length < at && at >= 0) {
if (values[at] == value) {
return at;
}
at = at + 1;
}
return -1;
}
The whole reason we usually talk about recursion is that it is usually used so that you have no "mutating" state. The variables and there values are the same for every value. You can break this, but it is usually considered beneficial. A quick stab at your problem produces something like
void int find(int[] sortedValues, int start, int end, int value) {
var midIndex = (start + end) / 2;
var mid = sortedValues[midIndex];
if (start == end) {
return mid == value ? midIndex : -1;
} else if (mid > value) {
return find(sortedValues, mid, end, value);
} else if (mid < value) {
return find(sortedValues, start, mid, value);
} else {
return midIndex;
}
}
However, this isn't perfect. It has known issues like edge cases that would cause a crash. It should definitely be cleaned up a little. If you want to really want to dip your toe into recursion, try a purely functional language where you cannot mutate, like Haskell, Elm, or maybe something a little impure like F#, Clojure, or Scala. Anyway have fun.

Is there a way to know what passed through a if statement

My problem is, that I need to now, what statements passed through a If statement. The code is as follows.
int[] Array = {value1,value2,value3}
foreach {int Value in Array)
{
if (Value < 4)
{
// Here i need to know what values passed through that were less that 4, like
// which one, value 1, value 2, and/or value 3
}
So is there a solution for a problem? I'm kind of new to programming.
My problem is that i do not need an else statement, i Need to know if value 1 or 2 or 3 passed through. Exactly which ones are less than 4. EDIT: fixed some mistakes, was in a rush, forgot to put the sign the other way. When they are less than 4, i need to now which values passed through. Ill prob repost tho. As i messed up. I really don't care for now which ones are greater, or the else statement, i skipped that part.
Edit2: I also came up with a solution, but i don't if its good. Should i run a loop when i store values in the if statement, making another if statement, to compare if the ones inside the if statement are the same on the outside, and then knowing which values passed through?
I'm not 100% positive if I understand the question but it seems you can use the else statement
if (Value > 4)
{
// Do your stuff for elements greater than 4
}
else
{
// Do your stuff for elements greater lower or equal than 4
}
How about use for instead of foreach, since you got index of array member, you will know which one passed through
int[] array = {value1, value2, value3}
for (int index = 0; index < array.Count(); index++)
{
if (array[index] < 4)
{
// do sth with index
}
}
int Array[] = {value1,value2,value3}
foreach {int Value in Array)
{
if (Value > 4)
{
// Here i need to know what elements passed through that were less that 4
}else if(Value < 4){
//values < 4 will execute this code
}
I'm going to make a few general suggestions that should hopefully be helpful. First of all, your conditional says if (Value > 4) so you will not go into that code block where you suggest figuring out which elements are less than 4. Instead you'd need an else. So here's one way;
int Array[] = {value1,value2,value3}
List<int> lessThanFour = new List<int>();
foreach {int Value in Array)
{
if (Value < 4)
{
lessThanFour.Add(Value);
Console.WriteLine(Value);
}
}
The above code puts each value which is less than four into a list so you can access them later. It also prints them to the console.
Another option would be to use LINQ;
var lessThanFour = Array.Where(x => x < 4);
foreach (int c in lessThanFor)
Console.WriteLine(c);
The above code uses the Where operator to create a new array with all ints in the original that have a value less than for. The statement x => x < 4 is best to think of in an iterative since where x is the current element. It works the same as the foreach loop. When you execute that code it basically says, for each int x in Array, if x is less than four add it to the result. Then I use a foreach below that to print out the results.
Your question is poorly framed I think but it sounds like you are looking for a switch case.
if (x < 4) {
switch (x) {
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
}

Categories