recursion - Different combinations of getting a total number with x amount of different smaller numbers MATLAB -


im trying create list represents different ways "change" (as in money) can given example this

 printcells(exchange([1,3,10],20)) 

and have output

ans = <0,0,2> <1,3,1> <2,6,0> <4,2,1> <5,5,0> <7,1,1> <8,4,0> <10,0,1> <11,3,0> <14,2,0> <17,1,0> <20,0,0> 

the cells in output represent how many times each indicie used in combination. im trying use recursion , don't know start

thanks in advance,

well, programmed recursion , got following:

function [] = change()     % specify inputs here     options = [1,3,10];     target  = 20;      global solutions;   solutions = [zeros(1, size(options,2))];     sum_up(options, target); end  function [] = sum_up(options, target)     clc;         recursive_sum(options, target, []); end  function [] = recursive_sum(options, target, partial)     global solutions;     s = 0;     i=1:size(partial,2)         s = s + partial(i);     end     if s == target         entry = [];         i=1:size(options, 2)             entry = [entry sum(partial == options(i))];         end         if ~sum(ismember(solutions(:,:), entry, 'rows'))             fprintf('%d, ', entry);             solutions = [solutions; entry];             fprintf('= %d\n', sum(partial));         end     end     if s >= target         return;     end     i=1:size(options,2)         recursive_sum(options, target, [partial options(i)]);     end end 

with output:

20, 0, 0, = 20 17, 1, 0, = 20 14, 2, 0, = 20 11, 3, 0, = 20 10, 0, 1, = 20 8, 4, 0, = 20 7, 1, 1, = 20 5, 5, 0, = 20 4, 2, 1, = 20 2, 6, 0, = 20 1, 3, 1, = 20 0, 0, 2, = 20 

note: matlab .m file should called change.m.

i hope helped out :)

code golf

and fun, here's extremely small version:

function[]=change()     o=[1,3,10]; t=20;     global l; l=[zeros(1,size(o,2))];     rs(o,t,[]); disp(l(2:end, :)); end  function[]=rs(o,t,p)     global l; s=0;     i=1:size(p,2); s=s+p(i); end     if s==t; e=[];         i=1:size(o, 2); e=[e sum(p==o(i))]; end         if ~sum(ismember(l(:,:),e,'rows')); l=[l; e]; end     end     if s>=t; return; end     i=1:size(o,2); rs(o,t,[p o(i)]); end end 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -