Triangle wave for indices (integers)
Alec Jacobson
May 04, 2012
Often I have N things and I want to assign them to n<<N groups/colors/positions etc. If I don't care too much about their order or distribution I might randomly assign them. If I care that sequential items go into different groups and that groups get the same number of items I might use:
ids = mod(indices,n)+1
Which plotted as a function of the indices looks like a sawtooth wave:

Another way to get non-repeating numbers, with near-equal distribution is to use a triangle wave, counting up to n and then back down to 1 and repeating:
ids = abs(mod(indices,n*2-2)-n+1)+1
which looks like:
