1

Say I have array indices 0 through 5

If I'm incrementing a counter over this array, I could do something like

i % 6

To make sure it never goes out of index. Is there a shorthand notation for the same thing for decrementing? I'm asking in general, not specific to any language

I know I can do

if (i < 0) i = 5
Jason
  • 808
  • 6
  • 25

3 Answers3

0

In some languages, i % 6 would still work even when decrementing - they define negative%positive as positive, so you get 5 when i decrements to -1.

In any language, (i + 6) % 6 would stay in range whether you increment or decrement.

jasonharper
  • 9,450
  • 2
  • 18
  • 42
0

If your chosen language supports modular arithmetic for user-defined types then incrimenting or decrimenting a modular integer will result in a value within the range of that modular integer.

Ada allows the user to specify modular types. The Ada solution for your question is

type Index_type is mod 6;
type Example is array(Index_Type) of Integer;

Iteration through the array, treating it as a circular buffer, can be done with a simple loop

declare 
   I : Index_Type := 0;
   A : Example;
begin
   loop
      A(I) := some_value;
      I := I - 1;
   end loop;
end;

Within the loop I can be incremented or decremented, and the arithmetic will always be modulo 6 in this case. In Ada such circular buffers are sometimes used in producer/consumer patterns. In that case there are separate read and write indices, with a check for a buffer full condition upon each write and a check for a buffer empty condition upon each read.

Jim Rogers
  • 4,822
  • 1
  • 11
  • 24
0

For positive integer n and non-negative counter i, you can define increment and decrement of the counter modulo n as arithmetic operations with positive integer values. Increment is i = (i + 1) % n, and decrement is i = (i + n - 1) % n.

Vyacheslav Lukianov
  • 1,913
  • 8
  • 12