2

I need to have a variable always changed to be within a certain range (0-5), working on rounds. For instance, if the variable hits 6, it should be changed to 0; if it hits -1, it should be changed to 5. Here's my pseudo, any ideas?

function get_further_letter($index = 5, $number = 3, $direction = "encode") {
    $count = 5;
    switch ($direction) 
    {
    case "encode":
        $index = $index + $number; //pushes the value of index to 8
        break;
    }
    // Start my attempt
    while ($index > $count)
    {
        $index = $index - $count;
    }
    // End my attempt
    return $index;
}

>> get_further_letter(5, 3); // 5 + 3 = 8, 8 is 1r3, so keep r3 as 0, 1, 2
2
>> get_further_letter(5, 4); // 5 + 4 = 9, 9 is 1r4, so keep r4 as 0, 1, 2, 3
3
>> get_further_letter(5, -7); // 5 + -7 = -2, -2 is -1r-2, so keep r-2 as 0, 1, 2, 3
4

Sorry for being vague, I'm very confused about how to get this to work, so it's a little difficult to articulate my requirements.

I got -2 for the last example as in my case specifically the value will be an array index. I'm not sure if this is actually going to happen.

5
  • 1
    its not clear what you want to do
    – Aris
    Dec 19, 2013 at 12:19
  • 1
    What do you want to do if the number is not within the range?
    – Syjin
    Dec 19, 2013 at 12:19
  • 1
    What exactly do you want to get as a result? Dec 19, 2013 at 12:20
  • 1
    it seems working. what is the issue you are facing
    – M I
    Dec 19, 2013 at 12:21
  • Sorry guys, I've provided a bit more clarification - hopefully it's a bit clearer now :S
    – Jamus
    Dec 19, 2013 at 12:38

1 Answer 1

3

The generic function that will keep a value within the range of [0 .. n) is this:

function fn($x, $n)
{
    return ($x % $n + $n) % $n;
}

The double modulo is to deal with negative numbers.

4
  • 1
    Wow. Such answer. Great success.
    – PeeHaa
    Dec 19, 2013 at 13:12
  • This code worked perfectly. @PeeHaa, I tried your solution, but I hit a variable it calculated differently than intended. But Jack's solution is a solid one-liner. Big thanks to everyone who helped! :)
    – Jamus
    Dec 19, 2013 at 14:33
  • Yes @Jamus already pointed out I am an idiot thanks :-)
    – PeeHaa
    Dec 19, 2013 at 14:38
  • 1
    Nononononono, you're amazing! I just found an issue when trying to use it. Thanks for your help all the same! Much appreciated.
    – Jamus
    Dec 19, 2013 at 14:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.