Jon Snow
Jon Snow

Reputation: 11882

Is there a better way to map an integer to a range of numbers?

I'm trying to map integers to numbers within range (1..7). 1 through 7 would be mapped to themselves, 8 to 1, 14 to 7, and so on.

The obvious candidate to do this is the modulo method %. However, 7 % 7 gives 0, which I do not want.

One can write the following method:

def int_map i
  (x = i % 7) == 0 ? 7 : x
end

I feel that there should be a better, more succinct way to do this. Is there? And how?

Upvotes: 1

Views: 648

Answers (4)

Jon Snow
Jon Snow

Reputation: 11882

Her's another solution. Quite easy to understand.

[7,1,2,3,4,5,6][i % 7]

Without specifying the array in full, you can do

(1..7).to_a.rotate(-1)[i % 7]

Upvotes: 0

Jon Snow
Jon Snow

Reputation: 11882

Here's another solution, without using modulo. The downside is that all this math makes confusing code.

i - (i - 1) / 7 * 7

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

Here is one more way to do this:

(1..7).to_a.rotate(i).last

Sample program given below:

def int_map i
    [1,2,3,4,5,6,7].rotate(i).last
end

int_map(1)
#=> 1
int_map(7)
#=> 7
int_map(8)
#=> 1
int_map(14)
#=> 7
int_map(15)
#=> 1

PS: May be bit inefficient as the value of i grows larger, but my tests did not indicate that. May be Ruby implementation is smart and handles multiple rotations in efficient manner.

Upvotes: 2

Sander de Jong
Sander de Jong

Reputation: 361

The result of the method should be:

(i - 1) % 7 + 1

Upvotes: 0

Related Questions