Saving Data in a recursive function to a list2019 Community Moderator ElectionWhat is tail recursion?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow do you split a list into evenly sized chunks?Getting the last element of a list in PythonHow to make a flat list out of list of lists?How to get the number of elements in a list in Python?How to concatenate two lists in Python?How to clone or copy a list?

Street obstacles in New Zealand

Giving a career talk in my old university, how prominently should I tell students my salary?

What materials can be used to make a humanoid skin warm?

Doubts in understanding some concepts of potential energy

Finitely many repeated replacements

Why couldn't the separatists legally leave the Republic?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

Is it possible that a question has only two answers?

What are some noteworthy "mic-drop" moments in math?

PTIJ: Why does only a Shor Tam ask at the Seder, and not a Shor Mu'ad?

How do we create new idioms and use them in a novel?

Is it possible to find 2014 distinct positive integers whose sum is divisible by each of them?

Why does cron require MTA for logging?

Trig Subsitution When There's No Square Root

Does a difference of tense count as a difference of meaning in a minimal pair?

Windows Server Datacenter Edition - Unlimited Virtual Machines

Does "Until when" sound natural for native speakers?

What is better: yes / no radio, or simple checkbox?

MySQL importing CSV files really slow

Signed and unsigned numbers

Are small insurances worth it?

What do *foreign films* mean for an American?

Which classes are needed to have access to every spell in the PHB?

Is it a Cyclops number? "Nobody" knows!



Saving Data in a recursive function to a list



2019 Community Moderator ElectionWhat is tail recursion?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow do you split a list into evenly sized chunks?Getting the last element of a list in PythonHow to make a flat list out of list of lists?How to get the number of elements in a list in Python?How to concatenate two lists in Python?How to clone or copy a list?










1















I'm working on a function which breaks down the given input into denominations using a recursive call.



At each step it recurses into two variants:



  1. Continue with the current coin: Add it to the list and recurse.

  2. Switch to the next coin: Increment coin pos and recurse.

In addition to printing out the combination of denominations captured in the list when remaining == 0, I intend to capture the value of that list and return it from the function.



Here's the code:



 static final int[] DENOMINATIONS = 9,5,3;

private static void change(int remaining, List<Integer> coins, int pos)

if (remaining == 0)

// This correctly prints the desired output.
// I want to return that exact value from the function.
System.out.println(coins);

else
if (remaining >= DENOMINATIONS[pos])
coins.add(DENOMINATIONS[pos]);
another.addAll(coins);
change(remaining - DENOMINATIONS[pos], coins, pos);
coins.remove(coins.size() - 1);

if (pos + 1 < DENOMINATIONS.length)
change(remaining, coins, pos + 1);


}


public static List<Integer> denominations(int amount)
List<Integer> result = new ArrayList<Integer>();
List<Integer> another = new ArrayList<Integer>();
change(amount, result, another ,0);
System.out.println(another.size());
return another;


public static void main(String[] args)
List<Integer> list = denominations(13);
System.out.println(list);



Output : [5, 5, 3]










share|improve this question
























  • Is this based on the SICP counting-change example?

    – Jodast
    Mar 7 at 5:55






  • 1





    I suppose it is.

    – Ubaid Showkat
    Mar 7 at 6:23















1















I'm working on a function which breaks down the given input into denominations using a recursive call.



At each step it recurses into two variants:



  1. Continue with the current coin: Add it to the list and recurse.

  2. Switch to the next coin: Increment coin pos and recurse.

In addition to printing out the combination of denominations captured in the list when remaining == 0, I intend to capture the value of that list and return it from the function.



Here's the code:



 static final int[] DENOMINATIONS = 9,5,3;

private static void change(int remaining, List<Integer> coins, int pos)

if (remaining == 0)

// This correctly prints the desired output.
// I want to return that exact value from the function.
System.out.println(coins);

else
if (remaining >= DENOMINATIONS[pos])
coins.add(DENOMINATIONS[pos]);
another.addAll(coins);
change(remaining - DENOMINATIONS[pos], coins, pos);
coins.remove(coins.size() - 1);

if (pos + 1 < DENOMINATIONS.length)
change(remaining, coins, pos + 1);


}


public static List<Integer> denominations(int amount)
List<Integer> result = new ArrayList<Integer>();
List<Integer> another = new ArrayList<Integer>();
change(amount, result, another ,0);
System.out.println(another.size());
return another;


public static void main(String[] args)
List<Integer> list = denominations(13);
System.out.println(list);



Output : [5, 5, 3]










share|improve this question
























  • Is this based on the SICP counting-change example?

    – Jodast
    Mar 7 at 5:55






  • 1





    I suppose it is.

    – Ubaid Showkat
    Mar 7 at 6:23













1












1








1








I'm working on a function which breaks down the given input into denominations using a recursive call.



At each step it recurses into two variants:



  1. Continue with the current coin: Add it to the list and recurse.

  2. Switch to the next coin: Increment coin pos and recurse.

In addition to printing out the combination of denominations captured in the list when remaining == 0, I intend to capture the value of that list and return it from the function.



Here's the code:



 static final int[] DENOMINATIONS = 9,5,3;

private static void change(int remaining, List<Integer> coins, int pos)

if (remaining == 0)

// This correctly prints the desired output.
// I want to return that exact value from the function.
System.out.println(coins);

else
if (remaining >= DENOMINATIONS[pos])
coins.add(DENOMINATIONS[pos]);
another.addAll(coins);
change(remaining - DENOMINATIONS[pos], coins, pos);
coins.remove(coins.size() - 1);

if (pos + 1 < DENOMINATIONS.length)
change(remaining, coins, pos + 1);


}


public static List<Integer> denominations(int amount)
List<Integer> result = new ArrayList<Integer>();
List<Integer> another = new ArrayList<Integer>();
change(amount, result, another ,0);
System.out.println(another.size());
return another;


public static void main(String[] args)
List<Integer> list = denominations(13);
System.out.println(list);



Output : [5, 5, 3]










share|improve this question
















I'm working on a function which breaks down the given input into denominations using a recursive call.



At each step it recurses into two variants:



  1. Continue with the current coin: Add it to the list and recurse.

  2. Switch to the next coin: Increment coin pos and recurse.

In addition to printing out the combination of denominations captured in the list when remaining == 0, I intend to capture the value of that list and return it from the function.



Here's the code:



 static final int[] DENOMINATIONS = 9,5,3;

private static void change(int remaining, List<Integer> coins, int pos)

if (remaining == 0)

// This correctly prints the desired output.
// I want to return that exact value from the function.
System.out.println(coins);

else
if (remaining >= DENOMINATIONS[pos])
coins.add(DENOMINATIONS[pos]);
another.addAll(coins);
change(remaining - DENOMINATIONS[pos], coins, pos);
coins.remove(coins.size() - 1);

if (pos + 1 < DENOMINATIONS.length)
change(remaining, coins, pos + 1);


}


public static List<Integer> denominations(int amount)
List<Integer> result = new ArrayList<Integer>();
List<Integer> another = new ArrayList<Integer>();
change(amount, result, another ,0);
System.out.println(another.size());
return another;


public static void main(String[] args)
List<Integer> list = denominations(13);
System.out.println(list);



Output : [5, 5, 3]







java algorithm list recursion coin-change






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 6:04







Ubaid Showkat

















asked Mar 7 at 5:06









Ubaid ShowkatUbaid Showkat

429




429












  • Is this based on the SICP counting-change example?

    – Jodast
    Mar 7 at 5:55






  • 1





    I suppose it is.

    – Ubaid Showkat
    Mar 7 at 6:23

















  • Is this based on the SICP counting-change example?

    – Jodast
    Mar 7 at 5:55






  • 1





    I suppose it is.

    – Ubaid Showkat
    Mar 7 at 6:23
















Is this based on the SICP counting-change example?

– Jodast
Mar 7 at 5:55





Is this based on the SICP counting-change example?

– Jodast
Mar 7 at 5:55




1




1





I suppose it is.

– Ubaid Showkat
Mar 7 at 6:23





I suppose it is.

– Ubaid Showkat
Mar 7 at 6:23












3 Answers
3






active

oldest

votes


















1














You seems to assume that java is passed by reference which is not true. Java methods are passed by value.



I have updated your code:



change method:



private static List<Integer> change(int remaining, List<Integer> coins, int pos) // Updated method return type;

if (pos < 0


denominations method:



public static List<Integer> denominations(int amount) 
return change(amount, new ArrayList<Integer>(), 0);



INPUT : 13
OUTPUT : [5, 5, 3]






share|improve this answer
































    1














    You would have to add return coins; at the and of change method, but you can keep it the way you have it. Returning and changing an array is a code smell as the method both operates on object (modifies it) and returns a result.



    To make it work, you can define your denomination method as follows:



    public static List<Integer> denominations(int amount) 
    List<Integer> result = new ArrayList<Integer>();
    change(amount, result, 0);
    return result;



    Edit:



    The list is empty because the only place it's changed is here:



    coins.add(DENOMINATIONS[pos]);
    change(remaining - DENOMINATIONS[pos], coins, pos);
    coins.remove(coins.size() - 1);


    Where an element is added and removed. It's what you have written that makes it empty:)



    Edit2:



    I would suggest passing around a second object, that would be a copy of the list you would like to return and is not modified.






    share|improve this answer

























    • I've tried that but it still returns an empty list. I modified my code according to your suggestions

      – Ubaid Showkat
      Mar 7 at 5:26











    • Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

      – Ubaid Showkat
      Mar 7 at 5:30











    • I have added a suggestion;)

      – Andronicus
      Mar 7 at 5:33


















    0














    change should return boolean that mean whether has been found an answer.



    So change body looks like this:



    if (remaining == 0) 
    return true;

    ...
    if (change(...)) return true;
    ...
    return false; // It's last line of body





    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55036453%2fsaving-data-in-a-recursive-function-to-a-list%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You seems to assume that java is passed by reference which is not true. Java methods are passed by value.



      I have updated your code:



      change method:



      private static List<Integer> change(int remaining, List<Integer> coins, int pos) // Updated method return type;

      if (pos < 0


      denominations method:



      public static List<Integer> denominations(int amount) 
      return change(amount, new ArrayList<Integer>(), 0);



      INPUT : 13
      OUTPUT : [5, 5, 3]






      share|improve this answer





























        1














        You seems to assume that java is passed by reference which is not true. Java methods are passed by value.



        I have updated your code:



        change method:



        private static List<Integer> change(int remaining, List<Integer> coins, int pos) // Updated method return type;

        if (pos < 0


        denominations method:



        public static List<Integer> denominations(int amount) 
        return change(amount, new ArrayList<Integer>(), 0);



        INPUT : 13
        OUTPUT : [5, 5, 3]






        share|improve this answer



























          1












          1








          1







          You seems to assume that java is passed by reference which is not true. Java methods are passed by value.



          I have updated your code:



          change method:



          private static List<Integer> change(int remaining, List<Integer> coins, int pos) // Updated method return type;

          if (pos < 0


          denominations method:



          public static List<Integer> denominations(int amount) 
          return change(amount, new ArrayList<Integer>(), 0);



          INPUT : 13
          OUTPUT : [5, 5, 3]






          share|improve this answer















          You seems to assume that java is passed by reference which is not true. Java methods are passed by value.



          I have updated your code:



          change method:



          private static List<Integer> change(int remaining, List<Integer> coins, int pos) // Updated method return type;

          if (pos < 0


          denominations method:



          public static List<Integer> denominations(int amount) 
          return change(amount, new ArrayList<Integer>(), 0);



          INPUT : 13
          OUTPUT : [5, 5, 3]







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 7 at 6:09

























          answered Mar 7 at 5:32









          MarkMark

          74618




          74618























              1














              You would have to add return coins; at the and of change method, but you can keep it the way you have it. Returning and changing an array is a code smell as the method both operates on object (modifies it) and returns a result.



              To make it work, you can define your denomination method as follows:



              public static List<Integer> denominations(int amount) 
              List<Integer> result = new ArrayList<Integer>();
              change(amount, result, 0);
              return result;



              Edit:



              The list is empty because the only place it's changed is here:



              coins.add(DENOMINATIONS[pos]);
              change(remaining - DENOMINATIONS[pos], coins, pos);
              coins.remove(coins.size() - 1);


              Where an element is added and removed. It's what you have written that makes it empty:)



              Edit2:



              I would suggest passing around a second object, that would be a copy of the list you would like to return and is not modified.






              share|improve this answer

























              • I've tried that but it still returns an empty list. I modified my code according to your suggestions

                – Ubaid Showkat
                Mar 7 at 5:26











              • Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

                – Ubaid Showkat
                Mar 7 at 5:30











              • I have added a suggestion;)

                – Andronicus
                Mar 7 at 5:33















              1














              You would have to add return coins; at the and of change method, but you can keep it the way you have it. Returning and changing an array is a code smell as the method both operates on object (modifies it) and returns a result.



              To make it work, you can define your denomination method as follows:



              public static List<Integer> denominations(int amount) 
              List<Integer> result = new ArrayList<Integer>();
              change(amount, result, 0);
              return result;



              Edit:



              The list is empty because the only place it's changed is here:



              coins.add(DENOMINATIONS[pos]);
              change(remaining - DENOMINATIONS[pos], coins, pos);
              coins.remove(coins.size() - 1);


              Where an element is added and removed. It's what you have written that makes it empty:)



              Edit2:



              I would suggest passing around a second object, that would be a copy of the list you would like to return and is not modified.






              share|improve this answer

























              • I've tried that but it still returns an empty list. I modified my code according to your suggestions

                – Ubaid Showkat
                Mar 7 at 5:26











              • Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

                – Ubaid Showkat
                Mar 7 at 5:30











              • I have added a suggestion;)

                – Andronicus
                Mar 7 at 5:33













              1












              1








              1







              You would have to add return coins; at the and of change method, but you can keep it the way you have it. Returning and changing an array is a code smell as the method both operates on object (modifies it) and returns a result.



              To make it work, you can define your denomination method as follows:



              public static List<Integer> denominations(int amount) 
              List<Integer> result = new ArrayList<Integer>();
              change(amount, result, 0);
              return result;



              Edit:



              The list is empty because the only place it's changed is here:



              coins.add(DENOMINATIONS[pos]);
              change(remaining - DENOMINATIONS[pos], coins, pos);
              coins.remove(coins.size() - 1);


              Where an element is added and removed. It's what you have written that makes it empty:)



              Edit2:



              I would suggest passing around a second object, that would be a copy of the list you would like to return and is not modified.






              share|improve this answer















              You would have to add return coins; at the and of change method, but you can keep it the way you have it. Returning and changing an array is a code smell as the method both operates on object (modifies it) and returns a result.



              To make it work, you can define your denomination method as follows:



              public static List<Integer> denominations(int amount) 
              List<Integer> result = new ArrayList<Integer>();
              change(amount, result, 0);
              return result;



              Edit:



              The list is empty because the only place it's changed is here:



              coins.add(DENOMINATIONS[pos]);
              change(remaining - DENOMINATIONS[pos], coins, pos);
              coins.remove(coins.size() - 1);


              Where an element is added and removed. It's what you have written that makes it empty:)



              Edit2:



              I would suggest passing around a second object, that would be a copy of the list you would like to return and is not modified.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 7 at 5:32

























              answered Mar 7 at 5:16









              AndronicusAndronicus

              4,16421429




              4,16421429












              • I've tried that but it still returns an empty list. I modified my code according to your suggestions

                – Ubaid Showkat
                Mar 7 at 5:26











              • Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

                – Ubaid Showkat
                Mar 7 at 5:30











              • I have added a suggestion;)

                – Andronicus
                Mar 7 at 5:33

















              • I've tried that but it still returns an empty list. I modified my code according to your suggestions

                – Ubaid Showkat
                Mar 7 at 5:26











              • Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

                – Ubaid Showkat
                Mar 7 at 5:30











              • I have added a suggestion;)

                – Andronicus
                Mar 7 at 5:33
















              I've tried that but it still returns an empty list. I modified my code according to your suggestions

              – Ubaid Showkat
              Mar 7 at 5:26





              I've tried that but it still returns an empty list. I modified my code according to your suggestions

              – Ubaid Showkat
              Mar 7 at 5:26













              Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

              – Ubaid Showkat
              Mar 7 at 5:30





              Yes you're right . And that because the items are being removed from the list. It's the value of list i want to return exactly when if(remaining == 0). Where modifications do you suggest?

              – Ubaid Showkat
              Mar 7 at 5:30













              I have added a suggestion;)

              – Andronicus
              Mar 7 at 5:33





              I have added a suggestion;)

              – Andronicus
              Mar 7 at 5:33











              0














              change should return boolean that mean whether has been found an answer.



              So change body looks like this:



              if (remaining == 0) 
              return true;

              ...
              if (change(...)) return true;
              ...
              return false; // It's last line of body





              share|improve this answer



























                0














                change should return boolean that mean whether has been found an answer.



                So change body looks like this:



                if (remaining == 0) 
                return true;

                ...
                if (change(...)) return true;
                ...
                return false; // It's last line of body





                share|improve this answer

























                  0












                  0








                  0







                  change should return boolean that mean whether has been found an answer.



                  So change body looks like this:



                  if (remaining == 0) 
                  return true;

                  ...
                  if (change(...)) return true;
                  ...
                  return false; // It's last line of body





                  share|improve this answer













                  change should return boolean that mean whether has been found an answer.



                  So change body looks like this:



                  if (remaining == 0) 
                  return true;

                  ...
                  if (change(...)) return true;
                  ...
                  return false; // It's last line of body






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 7 at 5:47









                  MoreFreezeMoreFreeze

                  1,20831529




                  1,20831529



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55036453%2fsaving-data-in-a-recursive-function-to-a-list%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page