Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/9964225a7600cf7561cb to your computer and use it in GitHub Desktop.
Save baweaver/9964225a7600cf7561cb to your computer and use it in GitHub Desktop.
Solving the phone pad problem without mutation
# Given an input string of 0 or more digits '2' - '9', list out all the possible strings
# from a typical phonepad digit-to-letter conversion (below), one per line
#
# 2: ABC 3: DEF 4: GHI 5: JKL 6: MNO 7: PQRS 8: TUV 9: WXYZ
LETTERS = [%w(A B C), %w(D E F), %w(G H I), %w(J K L), %w(M N O), %w(P Q R S), %w(T U V), %w(W X Y Z)]
def pad_mapper(*numbers)
numbers.map { |n| LETTERS[n - 2] }.reduce { |accumulated_words, letters|
letters.flat_map { |char|
accumulated_words.map { |word| word + char }
}
}
end
describe '#pad_mapper' do
context 'When given two digits with three letter keys' do
it 'returns nine results as letter pairs' do
expect(pad_mapper(2,3)).to eq(%w(
AD AE AF
BD BE BF
CD CE CF
))
end
end
context 'When given two digits with one three letter and one four letter key' do
it 'returns twelve results' do
expect(pad_mapper(3,7)).to eq(%w(
DP EP FP
DQ EQ FQ
DR ER FR
DS ES FS
))
end
end
end
@baweaver
Copy link
Author

@obfuscate on #ruby mentioned this method:

def pad_mapper2(*numbers)
  lambda { |x| x.shift.product *x }.call numbers.map { |n| LETTERS[n-2] }
end

So I did a bit of playing with it:

def pad_mapper3(*numbers)
  h, *t = numbers.map { |n| LETTERS[n-2] }
  h.product(*t)
end

@baweaver
Copy link
Author

Benchmarks:

[55] pry(main)> Benchmark.measure { 1_000.times { pad_mapper(2,2,3,4,5,6,7,8,9) } }.real
=> 7.02962506699987
[56] pry(main)> Benchmark.measure { 1_000.times { pad_mapper2(2,2,3,4,5,6,7,8,9) } }.real
=> 13.690460247998999
[57] pry(main)> Benchmark.measure { 1_000.times { pad_mapper3(2,2,3,4,5,6,7,8,9) } }.real
=> 13.6784067960034

Looks like the original beats it out in time. I'll have to experiment with why that is. Probably something to do with the way product is implemented as opposed to reduction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment