Created
October 31, 2015 21:30
-
-
Save kangkyu/7775d26467c17ae11b40 to your computer and use it in GitHub Desktop.
Today's Kata 10-29-2015
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Today's kata: | |
# Given a 3 or 4 digit number with distinct digits, return a sorted array of all the unique numbers that can be formed with those digits. | |
# ie, given 123, return [123, 132, 213, 231, 312, 321] | |
def same_digit_numbers(initial_num) | |
initial_num.to_s.split('').permutation.map {|e| e.join.to_i }.uniq.sort | |
end | |
def same_digit_numbers(initial_num) | |
num_string = initial_num.to_s | |
num_length = num_string.length | |
index_arrays(num_length).map do |index_array| | |
index_array.map { |index| num_string[index] }.join.to_i | |
end.uniq.sort | |
end | |
def index_arrays(num) | |
fold_up( tree_down( num.times.to_a ) ) | |
end | |
def tree_down(indices) | |
if indices.size == 1 | |
indices.pop | |
else | |
indices.map { |e| [e, tree_down(indices - [e])] } | |
end | |
end | |
def flat?(a) | |
a == a.flatten | |
end | |
def fold_up(full_nested) | |
if flat?( full_nested[-1] ) | |
full_nested | |
else | |
fold_up( full_nested.reduce [] { |result, e| result + fold(e) } ) | |
end | |
end | |
def fold(part_nested) | |
part_nested[-1].map { |e| part_nested[0..-2] + e } | |
end | |
gem 'minitest' | |
require 'minitest/autorun' | |
class TestRev < Minitest::Test | |
def test_permute | |
assert_equal [123, 132, 213, 231, 312, 321], same_digit_numbers(123) | |
end | |
def test_four_digits | |
assert_equal [1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2431, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321], same_digit_numbers(1234) | |
end | |
def test_for_another_number | |
assert_equal [234, 243, 324, 342, 423, 432], same_digit_numbers(243) | |
end | |
def test_for_duplication | |
assert_equal [111], same_digit_numbers(111) | |
end | |
def test_for_digit_duplication | |
assert_equal [122, 212, 221], same_digit_numbers(212) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 nice!!!