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

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme