新手问题 数字分组 1

bluexuemei · April 30, 2014 · Last by 5swords replied at May 01, 2014 · 2567 hits

question:0-9 共 10 个数字按 2-4-4 的长度分成 3 组,组成像 01-2345-6789 这样的组合,每组中的数字从小到大,列出所有的组合。 求简洁优雅高效的代码,高手们出招吧!

我能想出拆成好几个小方法的代码来,但是不好意思贴,还是等楼下一行党现身吧...

先完成再优化

(a=(0..9).to_a).combination(2).to_a.each {|b| (a-b).combination(4).to_a.each {|c| puts "#{b.join}-#{c.join}-#{(a-b-c).join}"}}

2:

(a=(0..9).to_a).combination(2).map {|b| (a-b).combination(4).map {|c| "#{b.join}-#{c.join}-#{(a-b-c).join}"}}.flatten

#2 楼 @5swords 我还以为要自己实现组合,原来有 combination 方法,学习了。

文档不熟啊 T_T

#3 楼 @blacktulip 哈哈,我也不熟,都是做一行党的时候逼的去翻文档,排列都有现成的。

arr = (0..9).to_a.shuffle
[arr[0, 2], arr[2, 4], arr[6, 4]].map &:sort

两行不行么

没看见所有

#2 楼 @5swords 这个方法和我的思路一样,但是如果是分为 5 组的话,这个方法就比较麻烦。有没有更通用的方法?

#6 楼 @bluexuemei

def combinations_string(a,n)
  return unless a.length == n.inject(:+)
  s=a.combination(n[0]).to_a
  n[1..-1].each do |i|
    s.length.times do
      x = s.pop
      (a-x).combination(i){|b| s.unshift x+b}
    end
  end
  s.map {|t| n.map{|r| t.shift(r).join }.join('-')}
end

combinations_string [*0..9],[2,4,2]
combinations_string [*0..9],[2,2,2,2,2]
You need to Sign in before reply, if you don't have an account, please Sign up first.