greatseth (owner)

Revisions

gist: 122690 Download_button fork
public
Description:
some Ruby code illustrating use of Modular Arithmetic
Public Clone URL: git://gist.github.com/122690.git
Embed All Files: show embed
modular_arithmetic.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# I've been reading a book on symmetry lately(http://is.gd/MGST),
# and the other day it touched on something interesting that it
# turns out my code could have benefited from very recently:
# Modular Arithmetic
 
# The use case was cycling through indexes of an array.
# I had an operation that I wanted cycle through an array of values
# for use each time it was run.
 
# Instead of something like this...
def rotate_index
  new_value = index + 1
  new_value = 0 if new_value >= array.size
  set_index(new_value)
end
 
# You could say this...
def rotate_index
  set_index((index + 1) % array.size)
end
 
# Math strikes again!