I have a list. If the value that you’ve entered is within that list – result will be returned. Even if value is outside the result’s range – result will be returned because of mod %. It’s really hard to explain my problem with words, so lets take a look at the code:
List<int> list1 = new List<int>(){ 0, 1, 2, 3, 4, 5, 6 };
int value = 3; // what's this number to us?
string result = "";
int starting_number = 3;
if (value == list1[(list1.IndexOf(starting_number) + 2) % list1.Count()])
{ result = "yeah"; }
else if (value == list1[(list1.IndexOf(starting_number) + 1) % list1.Count()])
{ result = "cool"; }
else if (value == list1[(list1.IndexOf(starting_number) + 0) % list1.Count()])
{ result = "one"; }
else if (value == list1[(list1.IndexOf(starting_number) - 1) % list1.Count()])
{ result = "noo"; }
else {result = "oops cant find it"; }
- starting_number. This number is constant. All measurments are made in relation to this number.
- value – the value that we’ve entered. we need to get the result for this value
- result – just a string
That’s how it works:
starting_number = 3, value = 2 => result = “noo” (because 2 = IndexOf(starting_number)- 1)
starting_number = 6, value = 0 => result = “cool” (6 + 1 = 0)
starting_number = 0, value = 6 => Error will occur. (0 – 1 = 6)
any ideas how to improve the code to get rid of this error? Basically I can grab values is they are “after” starting_number, but I cant grab them “before” starting_number.
-
in case of (6 + 1 = 0): list looks like this 6,0,1,2,3…
-
in case of (0 – 1 = 6): list should be this …4,5,6,0
if you have any questions please ask.. it’s really hard to explain the problem with words, but I guess examples made it more clear.
how do you grab values that are below starting_number?
If I understand correctly, you want to map all integers to range 0 to Count-1 and your current formula is
x % countwhich works only whenx > 0. Then if you want it to work for all values ofxtry this one(x % count + count) % count