Skip to content

Instantly share code, notes, and snippets.

@sstelfox
Created March 11, 2015 19:00
Show Gist options
  • Save sstelfox/727285d72ec19fabc4ec to your computer and use it in GitHub Desktop.
Save sstelfox/727285d72ec19fabc4ec to your computer and use it in GitHub Desktop.
I needed to uniquely identify a position in a three dimensional array of unique strings in both directions.
#!/usr/bin/env ruby
def x_values
%w(a b c d)
end
def y_values
%w(m n o p)
end
def z_values
%w(q r s t)
end
def identify_position(target_x, target_y, target_z)
x_values.index(target_x) +
(x_values.count * y_values.index(target_y)) +
((x_values.count * y_values.count) * z_values.index(target_z))
end
def identify_target(value)
z_index = (value / (x_values.count * y_values.count))
value -= z_index * (x_values.count * y_values.count)
y_index = (value / x_values.count)
value -= y_index * x_values.count
x_index = value
[x_values[x_index], y_values[y_index], z_values[z_index]]
end
puts identify_position('a', 'm', 'r').inspect
puts identify_target(16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment