Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through int values

Tags:

javascript

c#

I need some input.

Say you have an int-based Enum with values 1 through 10. If you then have a variable that is, say, value corresponding to 7, how can you easiest set it to next value in the given range without going out of bounds? If the value reaches the limit, it should reset itself to first in the range.

I want a one-liner solution to this. I don't want to do ++ and then check and reset value, plus it has to work in both C# and JavaScript. I suppose something in the Math object might be of help, I don't know...

thanks

like image 744
danijels Avatar asked Oct 27 '10 11:10

danijels


People also ask

Can you iterate through an int?

Since integers, individualistically, are not iterable, when we try to do a for x in 7 , it raises an exception stating TypeError: 'int' object is not iterable .

How do you iterate through integer digits?

The first method to iterate through digits of a number is the use of iter() function. It accepts the string value as the argument. Therefore you have to first typecast the integer value and then pass it into it.

How do you iterate through a number in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


1 Answers

Increment, subtract 1, then modulo, then add 1 (since your Enum is 1-based).

((++i - 1) % N + 1

(N=10, the maximum value your Enum can take on.)

like image 95
Fred Foo Avatar answered Nov 07 '22 09:11

Fred Foo