Skip to content

Instantly share code, notes, and snippets.

@smkopp92
Created April 5, 2017 21:05
Show Gist options
  • Save smkopp92/4fc19212b1cf942c1b0c191f82bb42f4 to your computer and use it in GitHub Desktop.
Save smkopp92/4fc19212b1cf942c1b0c191f82bb42f4 to your computer and use it in GitHub Desktop.
require 'pry'
# You're given a vector of vectors of words, e.g.:
# [['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']].
#
# Write a generalized function that prints all combinations of one word from the first vector, one word from the second vector, etc.
# The solution may not use recursion.
#
# NOTE: the *number of vectors* and number of elements within each vector may vary.
class ArrayThingy
attr_reader :array
def initialize(array)
@array = array
@array_point_map = array_start_length_map
@combos = []
end
def array_combos
array_count = 0
new_combo = []
while @combos.length < total_combo_count
new_combo << array[array_count][@array_point_map[array_count]]
if new_combo.length == array.length
@combos << new_combo
new_combo = []
array_count = 0
update_counter_map
else
array_count += 1
end
end
print_combos
end
def total_combo_count
count = 1
array.each do |subarray|
count = count * subarray.length
end
count
end
def array_end_length_map
array.map { |sub_array| sub_array.length }
end
def array_start_length_map
array.map { |sub_array| 0 }
end
def update_counter_map
checking = true
counter = 0
while checking && counter < array.length
if @array_point_map[counter] == array_end_length_map[counter] - 1
@array_point_map[counter] = 0
counter += 1
else
@array_point_map[counter] += 1
checking = false
end
end
end
def print_combos
@combos.each do |combo|
puts combo.join(" ")
end
end
end
array = ArrayThingy.new([['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']])
array.array_combos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment