Last active
August 12, 2016 14:04
-
-
Save kymmt90/8d94d507700fd18df41a6665c23ce4ea to your computer and use it in GitHub Desktop.
Ruby で順列
This file contains 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
def my_permutation(sequence, r = nil) | |
r = sequence.size if r.nil? || sequence.size < r | |
result = [] | |
enumerate(sequence, r, [], result) | |
result | |
end | |
def enumerate(sequence, r, one_enumeration, result) | |
if one_enumeration.size == r | |
result << one_enumeration.dup | |
return | |
end | |
sequence.each do |n| | |
# 再帰時にはコピーを渡す | |
dup_sequence = sequence.dup | |
dup_one_enumeration = one_enumeration.dup | |
# sequence から取り除いた要素を列挙用配列へ追加 | |
dup_sequence.delete(n) | |
dup_one_enumeration << n | |
enumerate(dup_sequence, r, dup_one_enumeration, result) | |
# 列挙用配列へ追加した要素を取り除き sequence へ戻す | |
dup_sequence << n | |
dup_one_enumeration.delete(n) | |
end | |
end | |
p my_permutation(['a', 'b', 'c']) | |
p my_permutation(['a', 'b', 'c', 'd'], 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment