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?
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:
- Continue with the current coin: Add it to the list and recurse.
- 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
add a comment |
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:
- Continue with the current coin: Add it to the list and recurse.
- 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
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
add a comment |
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:
- Continue with the current coin: Add it to the list and recurse.
- 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
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:
- Continue with the current coin: Add it to the list and recurse.
- 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
java algorithm list recursion coin-change
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
add a comment |
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
add a comment |
3 Answers
3
active
oldest
votes
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]
add a comment |
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.
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
add a comment |
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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]
add a comment |
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]
add a comment |
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]
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]
edited Mar 7 at 6:09
answered Mar 7 at 5:32
MarkMark
74618
74618
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Mar 7 at 5:47
MoreFreezeMoreFreeze
1,20831529
1,20831529
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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