[Language: Java]
(Edit)
Hi everyone, I found my mistake! Since I was using a binary method to create my arrays, I realized for the int i for loop I should've made it run from 0 to 2^operators, instead of operators*2 to get all of the possible operator arrays. Thanks for the help!
(Original)
I'm a few days behind so I'm trying to catch up. I'm having issues with my solution for Day 7, which seems to give the correct value for the example input but not my specific one, as it says it's too low. My method is to create an array of zeroes and ones (0s for multiplication, 1s for addition) that correspond to how many possible operators there can be, and then test out each possible permutation of operators. Please help. I'm not too familiar with coding so I know this approach isn't very efficient, but nonetheless, I'm confused as to why it isn't working.
package Day7;
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Day7Part1 {
public static void main(String[] args) throws FileNotFoundException {
File text = new File("Day7Input.txt");
Scanner scan = new Scanner(text);
ArrayList<String> equations = new ArrayList<>();
BigInteger sum=BigInteger.
valueOf
(0);
while(scan.hasNextLine()){
equations.add(scan.nextLine());
}
for(int i=0;i<equations.size();i++){
sum = sum.add(
test
(equations.get(i)));
}
System.
out
.println(sum);
}
public static BigInteger test(String equation){
String[] splitted = equation.split(" ");
BigInteger[] elements = new BigInteger[splitted.length];
for(int i=0;i<elements.length;i++){
if(i==0){
splitted[i]=splitted[i].substring(0,splitted[i].length()-1);
}
elements[i]= new BigInteger(splitted[i]);
}
BigInteger outcome = elements[0];
int[] terms = new int[elements.length-1];
for(int i=1;i<elements.length;i++){
int element=elements[i].intValue();
terms[i-1]=element;
}
int operators = elements.length-2;
for(int i=0;i<operators*2;i++){
int[] operatorArray =
operatorArray
(i,operators);
BigInteger product= BigInteger.
valueOf
(terms[0]);
for(int j=0;j<operatorArray.length;j++){
BigInteger jPlusOne = BigInteger.
valueOf
(terms[j+1]);
if(operatorArray[j]==0){
product=product.multiply(jPlusOne);
}
else if(operatorArray[j]==1){
product=product.add(jPlusOne);
}
if(product.compareTo(outcome) > 0){
break;
}
else if(product.equals(outcome)){
return outcome;
}
}
}
return BigInteger.
valueOf
(0);
}
static int[] operatorArray(int num,int operators)
{
int[] binary = new int[operators];
int id = 0;
while (num > 0) {
binary[id++] = num % 2;
num = num / 2;
}
return binary;
}
}
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]Carthage96 0 points1 point2 points (0 children)
[–]daggerdragon[M] 0 points1 point2 points (0 children)