How to combination/permutation in ruby?

后端 未结 3 1068
清歌不尽
清歌不尽 2021-01-18 19:46

I\'ve this familiar question that looks like permutation/combination of the Math world.

How can I achieve the following via ruby?

badges = \"1-2-3\"
         


        
3条回答
  •  攒了一身酷
    2021-01-18 20:12

    Array#permutation(n) will give you all the permutations of length n as an Array of Arrays so you can call this with each length between 1 and the number of digits in badges. The final step is to map these all back into strings delimited with -.

    badges = "1-2-3"
    
    badges_split = badges.split('-')
    
    permutations = []
    
    (1..badges_split.size).each do |n|
        permutations += badges_split.permutation(n).to_a
    end
    
    result = permutations.map { |permutation| permutation.join('-') }
    

    Update: I think Alex's use of reduce is a more elegant approach but I'll leave this answer here for now in case it is useful.

提交回复
热议问题