Triangle wave for indices (integers)

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:
index mod sawtooth

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:
index mod triangle

Tags: , , , , ,

Leave a Reply