ColinE
ColinE

Reputation: 70122

Determine whether an number is one greater or one less than another in a circular set

I am kicking myself for having to ask this ...I can solve this with a couple of simple 'if' statements, but I am sure there is a simpler way!

I have a paging control which allows the user to move one page left or one page right. Each page has an index. The pages cycle, therefore if you have three pages and you keep moving right the user sees:

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

I have the current page index and the previous page index. How can I determine if the user has paged right or left?

Thanks!

Upvotes: 4

Views: 941

Answers (4)

Ani
Ani

Reputation: 113402

There isn't enough information to answer the question; it isn't always possible to tell if the user moved "right" or "left" with just the current and previous indices.

For example, let's say current = 0, and previous = 1.

Did the user move left or did the user move right and there was an overflow to 0 because there are only two pages? It isn't possible to tell.

If you don't know the number of pages, here are a few 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, it's probably more intuitive to do:

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

but there still isn't enough information to tell what the user did when there are only one or two pages : in these cases, moving left and right produce equivalent "results". If you must differentiate left and right even in these situations, the obvious solution would be to simply store the direction in which the user paged separately. You probably shouldn't try to compute something that can't be computed. :)

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

One if should be enough:

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

If the pages cycled, the second set of conditions comes into play.

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

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

Upvotes: 0

Peter Kelly
Peter Kelly

Reputation: 14391

bool movedRight = current > previous;

Upvotes: -1

Related Questions