Suppose one has 35 cents then what are the various combinations of quarters, dimes, cents and fives which can make this amount.
For ex:
1 quarter, 1 dimes
1 quarter, 2 fives
1 quarter, 1 fives, 5 cents
.......
Following is the program which generates these combinations:
import java.util.HashSet;
import java.util.Set;
public class Cents {
public Set<String> s = new HashSet<String>();
public void getChange(int nos, int qua, int dimes, int fives, int cents){
if ( nos == 0){
s.add("" + qua + "," + dimes + "," + fives + "," + cents);
return;
}
if (nos < 0){
return;
}
if ( (nos-25) >= 0)
getChange((nos-25), (qua+1), dimes, fives, cents);
if ( (nos-10) >= 0)
getChange((nos-10), qua, (dimes+1), fives, cents);
if ( (nos-5) >= 0)
getChange((nos-5), qua, dimes, (fives+ 1), cents);
if ( (nos-1) > 0)
getChange((nos-1), qua, dimes, fives, (cents+ 1));
}
public static void main(String[] args) {
Cents c = new Cents();
c.getChange(35, 0, 0 , 0 , 0);
for (String s : c.s){
System.out.println(s);
}
}
}
For ex:
1 quarter, 1 dimes
1 quarter, 2 fives
1 quarter, 1 fives, 5 cents
.......
Following is the program which generates these combinations:
import java.util.HashSet;
import java.util.Set;
public class Cents {
public Set<String> s = new HashSet<String>();
public void getChange(int nos, int qua, int dimes, int fives, int cents){
if ( nos == 0){
s.add("" + qua + "," + dimes + "," + fives + "," + cents);
return;
}
if (nos < 0){
return;
}
if ( (nos-25) >= 0)
getChange((nos-25), (qua+1), dimes, fives, cents);
if ( (nos-10) >= 0)
getChange((nos-10), qua, (dimes+1), fives, cents);
if ( (nos-5) >= 0)
getChange((nos-5), qua, dimes, (fives+ 1), cents);
if ( (nos-1) > 0)
getChange((nos-1), qua, dimes, fives, (cents+ 1));
}
public static void main(String[] args) {
Cents c = new Cents();
c.getChange(35, 0, 0 , 0 , 0);
for (String s : c.s){
System.out.println(s);
}
}
}
No comments:
Post a Comment