Replacing floor operation with modulus

1.7k Views Asked by At

I have this array of characters

aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffffgggggggggghhhhhhhhhhiiiiiiiiiijjjjjjjjjjkkkkkkkkkkllllllllllmmmmmmmmmmnnnnnnnnnnooooooooooppppppppppqqqqqqqqqqrrrrrrrrrrssssssssssttttttttttuuuuuuuuuuvvvvvvvvvvwwwwwwwwwwxxxxxxxxxxyyyyyyyyyyzzzzzzzzzz

it's the alphabet in order, with 10 of each character, so that's 260 characters.

Given an index between 0 and 259, how can I create a function that can return the expected letter with only knowledge of the alphabet itself (a-z)?

One simple way would be:

index_of_letter = floor(index/10);

so if index is 9, it would yield floor(.9), which is 0, which would be the letter a in the standard western alphabet. If the index was 259, that would yield floor(25.9) which would in turn yield z.

However, isn't there a way to do this with modulus instead of using a floor operator?

I can't figure out how to do this with mod, but I am sure there is away to do! Anyone know how I could do this with mod?

2

There are 2 best solutions below

2
On

Sure. For positive $x, k$ integers, and % being the usual mod operator

floor(x/k) = (x - x % k)/k

As dxiv notes, this might be redundant (depending on the language you're using) - often, for integer types, $x/y$ is already a $floor$ operation.

One issue here is that various languages will disagree about the results when $x<0$. For example some languages believe $(-1)$ % $3 = -1$; while others insist that $(-1)$ % $3 = 2$. So that should be kept in mind.

Also, this relationship can be used when the language does not support % for non-integers; because

x % k = x - k*floor(x/k)

(again, keep track of what you want to happen with $x<0$).

0
On

If the language is C or Java by any chance, and if index is an integer variable (not floating point), then all you need to do is:

index_of_letter = index / 10;

since the / operator performs integer division with truncation (for non-negative operands), so taking the floor of the result is redundant.