genChoices.rb


    #
    # 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"
    #

About Adrian

Wohnort: Siegburg Tätigkeit: Student (Wirtschaftsinformatik)
This entry was posted in IT, Ruby, snippets and tagged , , . Bookmark the permalink.

Kommentare sind deaktiviert.