Determine if a number will be more or less than one in a circular set

I kick myself for asking about it ... I can solve it with a few simple โ€œifโ€ statements, but I'm sure there is an easier way!

I have a paging control that allows the user to move one page to the left or one page to the right. Each page has an index. Page loops, so if you have three pages and you continue to move correctly, the user sees:

0 => 1 => 2 => 0 => 1 ... 

I have the index of the current page and the index of the previous page. How to determine if a user has been unloaded right or left?

Thanks!

+4
source share
4 answers

Not enough information to answer the question; it is not always possible to say whether the user has moved "right" or "left" only with current and previous indices.

For example, say current = 0 and previous = 1 .

Has the user moved left or has the user moved right and overflowed to 0 because there are only two pages? Impossible to say.

If you do not know the number of pages, here are some rough solutions:

 // Doesn't handle wrap arounds properly. bool movedRight = current == previous + 1; // Assumes that being at the start point always means an overflow occurred. bool movedRight = (current == previous + 1) || current == 0; // Assumes that being at the start point always means an overflow occurred, // except when we were previously at the second element. bool movedRight = (current == previous + 1) || (current == 0 && previous != 1); 

If you know the number of pages, perhaps more intuitively:

 // Can't disambiguate when numPages == 1 or 2 bool movedRight = current == (previous + 1) % numPages; 

but thereโ€™s still not enough information to tell what the user did when there is only one or two pages: in these cases, moving left and right gives equivalent โ€œresultsโ€. If you must distinguish between left and right even in these situations, the obvious solution would be to simply keep the direction in which the user is called separately. You should probably not try to figure out what cannot be calculated. :)

+3
source
 dir = (current == ( previous + 1 ) % num_pages ) ? right : left 
0
source

One if should be enough:

 if(prev + 1 == current || (current == 0 && prev > 1)) // right else // left 

If the pages are cyclical, a second set of conditions comes into play.

0
source
 bool movedRight = current > previous; 
-1
source

Source: https://habr.com/ru/post/1342977/


All Articles