Problem 31
Coin sums
In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), £2 (200p)
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
硬币求和
英国的货币单位包括英镑£和便士p,在流通中的硬币一共有八种:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), £2 (200p)
以下是组成£2的其中一种可行方式:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
不限定使用的硬币数目,组成£2有多少种不同的方式?
package projecteuler;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import org.junit.Test;
public class Prj31 {
/**
* In England the currency is made up of pound, £, and pence, p, and there
* are eight coins in general circulation:
*
* 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to
* make £2 in the following way:
*
* 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2
* be made using any number of coins?
*/
@Test
public void test() {
Calculator cal = new Calculator();
int[] val = new int[8];
cal.calculate(0, 200, val);
System.out.println(cal.getCount());
}
public static class Calculator {
private static final String FILE_PATH = "C:\\Users\\1440\\Desktop\\prj31.txt";
static {
File f = new File(FILE_PATH);
f.delete();
}
private int count = 0;
private int[] values = { 1, 2, 5, 10, 20, 50, 100, 200 };
public void calculate(int index, int total, int[] val) {
int len = val.length;
if (total < 0) {
return;
}
if (total == 0) {
if (checkSum(val, 200, values)) {
count++;
print_arr(val);
}
return;
}
if (index == len - 1) {
if (total % values[len - 1] == 0) {
val[len - 1] = total / values[len - 1];
if (checkSum(val, 200, values)) {
count++;
print_arr(val);
}
} else {
}
return;
}
for (int i = 0; i <= total / values[index]; i++) {
int[] copy = Arrays.copyOf(val, val.length);
copy[index] = i;
int totalCopy = total - i * values[index];
calculate(index + 1, totalCopy, copy);
}
}
private boolean checkSum(int[] arr, int sum, int[] _values) {
int sum1 = 0;
for (int i = 0; i < arr.length; i++) {
sum1 += arr[i] * _values[i];
}
return sum1 == sum;
}
public int getCount() {
return count;
}
public void print_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
System.out.println();
//saveArr(FILE_PATH, arr);
}
private void saveArr(String path, int[] arr) {
File file = new File(path);
try {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true)));
for (int i = 0; i < arr.length; i++) {
writer.append(String.valueOf(arr[i]) + ",");
}
writer.write("\t\n");
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}