文字列の組み合わせをアルファベト順で並び替える問題。
今回も組み込みメソッドで対応。 instance method Array#permutation (Ruby 2.4.0)
Codeevalとかやると、かゆいところに手が届くrubyは非常に良いと実感できます。
(本来的にはこれを素で実装しろということなんでしょうが、まぁ便利だしいいよね。)
CHALLENGE DESCRIPTION:
Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper case letters < lower case letters. The sorting should be performed in ascending order.
INPUT SAMPLE:
Your program should accept a file as its first argument. The file contains input strings, one per line.
hat abc Zu6
OUTPUT SAMPLE:
aht,ath,hat,hta,tah,tha abc,acb,bac,bca,cab,cba 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6
CONSTRAINTS:
- The text is case-sensitive: ‘a’ and ‘A’ are different characters.
- The input consists of 40 text lines.
- The maximum size of the text is 10 KB.
My Code
#!/usr/bin/env ruby -w def all_permutations(str) str.split("").permutation(str.size).map(&:join).sort.join(",") end ARGF.each_line do |line| puts all_permutations(line.chomp!) end