Algorithm to show all combinations of numbers in the list -


how build recursive function show possibilities of signs in list of numbers e.g. (5, 3, 12, 9, 15). list won't change, signs each number.

for example, results be:
(-5, 3, 12, 9, 15)
(-5, -3, 12, 9, 15)
(-5, -3, -12, 9, 15)
(-5, -3, -12, -9, 15)

and on, until combinations of list displayed.

i've tried few different ways, including trying adapt code other similar questions here, majority of them include changing list itself.

thanks!

when implementing recursive function, need think 2 cases: base case , recursive case.

in base case, function doesn't call recursively. may work in case, or may nothing because work has been done.

in recursive case, function little bit of work closer goal, calls recursively rest of work done.

here's way break down problem recursive function.

in recursive case, “little bit of work” setting sign of 1 number in list positive, , also set sign of number negative. need recurse after both assignments, because need generate combinations each sign.

in base case, of numbers have had signs set, print list of numbers.

in python, example, start setting function take list of numbers, , index of next number needing sign set. start, next number first number in list, @ index 0:

def allsigncombinations(numbers, nextnumberindex=0): 

the base case happens when nextnumberindex equal len(numbers), meaning there no numbers left needing signs set:

    if nextnumberindex == len(numbers):         print numbers 

otherwise, “little bit of work”. set sign of next number both positive , negative, , recurse each sign. when recurse, tell next call work starting @ next number in list, if there one:

    else:         numbers[nextnumberindex] = abs(numbers[nextnumberindex])         allsigncombinations(numbers, nextnumberindex + 1)         numbers[nextnumberindex] = -numbers[nextnumberindex]         allsigncombinations(numbers, nextnumberindex + 1) 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -