In: Computer Science
In the java programming language.
How would you find if numbers in an array element add up to a certain sum so for example if my array element consists of: INPUT: 200, 10, 50, 20 and my output asks if these elements add to: 210? YES (200+10) 260? YES (200+10+50) 30? NO What method would you suggest to look through the elements in an array (which im going to add through a text file) and determine if these sums exist in O(n^2)?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SumChecker {
private static final String FILENAME = "array_nums.txt";
public static void main(String[] args) {
Scanner fileReader;
int arr[] = null;
int count = 0;
try
{
fileReader = new Scanner(new File(FILENAME));
// 1st line contains all the elements of the array separated by
comma
String[] data = fileReader.nextLine().trim().split(",");
arr = new int[data.length];
for(String s : data)
arr[count++] = Integer.parseInt(s);
// second line contains all the sums to be checked separated by
comma
String[] sumData = fileReader.nextLine().trim().split(",");
for(String sumD : sumData)
{
checkSum(arr, Integer.parseInt(sumD));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println(FILENAME + " could not be found!
Exiting..");
System.exit(0);
}
}
private static void checkSum(int arr[], int sum)
{
int sumTemp = sum;
int arrTemp[] = new int[arr.length];
int count = 0;
for(int i = 0; i < arr.length; i++)
{
if((sumTemp - arr[i]) >= 0)
{
sumTemp = sumTemp - arr[i];
arrTemp[count++] = arr[i];
}
}
int add = 0;
for(int i = 0; i < count; i++)
add += arrTemp[i];
if(add == sum)
{
System.out.print(sum + " : YES (");
for(int i = 0; i < count; i++)
{
if(i == count - 1)
System.out.println(arrTemp[i] + ")");
else
System.out.print(arrTemp[i] + " + ");
}
}
else
System.out.println("Sorry, no such elements add up to a sum of " +
sum);
}
}
******************************************************** SCREENSHOT ********************************************************