Skip to content

Instantly share code, notes, and snippets.

@addisaden
Created October 23, 2011 21:32
Show Gist options
  • Save addisaden/1307911 to your computer and use it in GitHub Desktop.
Save addisaden/1307911 to your computer and use it in GitHub Desktop.
Rubyfunktion, welche alle Kombinationsmöglichkeiten der Argumentenliste zurück gibt
#
# genChoices | Gibt alle Kombinationsmöglichkeiten der Argumentenliste zurück. @ writedown.eu
#
def genChoices(*args)
choices = []
return args if args.length <= 1
(0...args.length).each { |pos|
if pos > 0
temp = choices.dup
temp.each { |e|
restOfArgs = e[(pos+1)...args.length].dup
toRework = e[0...pos]
pointsTo = [e[pos]].dup
# puts "-"*10
# puts "#{ toRework.inspect } | #{ pointsTo.inspect } | #{ restOfArgs.inspect }"
(0...pos).reverse_each { |pointer|
# generieren der bereiche
leftToPointer = toRework[0...pointer].dup
rightToPointer = toRework[pointer..pos].dup
#
choices << (leftToPointer + pointsTo + rightToPointer + restOfArgs).dup
}
}
elsif pos == 0
choices << args.dup
end
}
return choices
end
puts "genChoices(:a,:b,:c) => " + genChoices(:a,:b,:c).inspect
# => "genChoices(:a,:b,:c) => [[:a, :b, :c], [:b, :a, :c], [:a, :c, :b], [:c, :a, :b], [:b, :c, :a], [:c, :b, :a]]"
#
print "genChoices( *( (0...10).to_a ) ) Time: #{ Time.now }"
elementCount = genChoices( *( (0...10).to_a ) ).length
puts " - #{ Time.now } Elements: #{ elementCount }"
# => "genChoices( *( (0...10).to_a ) ) Time: 2011-10-23 23:29:16 +0200 - 2011-10-23 23:30:09 +0200 Elements: 3628800"
#
puts "fak(10) = #{ (1..10).inject { |x,y| x*y } }"
# => "fak(10) = 3628800"
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment