{{ message }}

Instantly share code, notes, and snippets.

Last active Nov 17, 2017
Code Challenge: Map out moves on a matrix to spell words

# Basic Idea

You have a matrix of letters, like this, sort of like an on screen keyboard you'd use to login to Netflix on your TV

``````a b c d e f

g h i j k l

m n o p q r

s t u v w x

y z
``````

And the task is to write some code that will take a word and calculate the "moves" required to spell the given word.

• the word is an argument
• the number of columns is configurable.
• A is the starting posision
• Two consecutive letters can just hit "enter/select" twice (see "output" section below)

Output

• D for a down move
• U for an up move
• X for "enter/select"

Should be something like this

For example, spell "dog" using the matrix above

`["RRRX","DDLX", "ULLX"]`

My solution is below

 class WordPath def initialize(word, columns) @matrix_columns = columns @word = word.upcase #upcase it so .ord works predictably @positions = [] @moves = [] @last_position = [] @position_counter = 0 #create an array of positions @word.split("").each do |letter| @positions << self.get_position(letter) end #iterate the positions and generate a move. @positions.each do |position| if @last_position.count < 1 @last_position = [1,1] else @last_position = @positions[@position_counter - 1 ] end @position_counter = @position_counter + 1 @moves << self.get_next_move(position, @last_position) end end def get_moves @moves end def get_next_move(curpos, lastpos) #assembles and returns the next complete move # just to make things clearer ... cur_row = curpos cur_col = curpos last_row = lastpos last_col = lastpos submoves = position_mover(last_row, cur_row, "v") + position_mover(last_col, cur_col, "h") + ["X"] return submoves end def position_mover(from, to, direction) # given two positions, and a "v" or "h" to indicate direction # will return a sub-move move = [] direction_indicator = from - to positions_to_move = direction_indicator.abs # sloppy, theres likely better way to do this if direction == "v" move << "D" * positions_to_move if direction_indicator < 0 move << "U" * positions_to_move if direction_indicator > 0 end if direction == "h" move << "R" * positions_to_move if direction_indicator < 0 move << "L" * positions_to_move if direction_indicator > 0 end return move end def get_position(letter) #returns the position of a letter in the current matrix alpha_position = (letter.ord) - 64 row = (alpha_position / @matrix_columns.to_f) + 1 column = (alpha_position % @matrix_columns) row = row - 1 if column == 0 column = @matrix_columns if column == 0 # no modulus means the last position in a row return [row.floor, column] end end WORD = ARGV COLUMNS = ARGV.to_i wp = WordPath.new(WORD, COLUMNS); puts "For the word #{WORD}" wp.get_moves.each do |move| puts move.inspect end