Question

In: Computer Science

Implement a function that reads numbers in from a file with one number per line and...

Implement a function that reads numbers in from a file with one number per line and outputs all the possible sums that can be formed by subsets of the numbers. For instance, if the numbers in the file are 1 2 4, then the output would be 0, 1, 2, 4, 3, 5, 6, 7. Note that 0 is in the output because it uses none of the numbers, while 7 is the sum of all of the numbers.

// Return all sums that can be formed from subsets of elements in arr
public static ArrayList<Integer> allSums( ArrayList<Integer> arr ) { ... }

Solutions

Expert Solution

FUNCTION

// Function to remove duplicates from an ArrayList
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
{
  
// Create a new ArrayList
ArrayList<T> newList = new ArrayList<T>();
  
// Traverse through the first list
for (T element : list) {
  
// If this element is not present in newList
// then add it
if (!newList.contains(element)) {
  
newList.add(element);
}
}
  
// return the new list
return newList;
}
//method to generate the all combination of numbers
public static void generate()
{
String fname;int i,j,a,b,c,sum=0;
//create two arraylists
ArrayList<Integer> alist=new ArrayList<Integer>();
ArrayList<Integer> alist1=new ArrayList<Integer>();
//create scanner object
Scanner scan = new Scanner(System.in);
  
/* enter filename with extension to open and read its content */
  
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
  
/* this will reference only one line at a time */
  
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
  
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
  
while((line = bufferedReader.readLine()) != null)
{
//add the elements into arraylist
       alist.add(Integer.parseInt(line));
}
//close the file
bufferedReader.close();
//add 0 as first element into alist1
alist1.add(0);
//add all elements into the alist1
for (i = 0; i < alist.size();i++)
   {
           sum=sum+(int)alist.get(i);//find the sum      
   alist1.add(alist.get(i));      
   }
//compute the combinations with all elements of alist
for (i = 0; i < alist.size();i++)
   {
for(j=i+1;j<alist.size();j++)
{
a=(int)(alist.get(i));

b=(int)(alist.get(j));
c=a+b;
alist1.add(c);//add the combinations to alist1

}       
   }
alist1.add(sum); //add the sum of all elements into alist1

// Remove duplicate elements if any
ArrayList<Integer>
newList = removeDuplicates(alist1);
System.out.println(newList); //display the new list as the result
}

catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}

IMPLEMENTATION OF FUNCTION IN JAVA PROGRAM

import java.util.Scanner;
import java.util.*;
import java.io.*;

public class JavaProgram
{
// Function to remove duplicates from an ArrayList
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
{
  
// Create a new ArrayList
ArrayList<T> newList = new ArrayList<T>();
  
// Traverse through the first list
for (T element : list) {
  
// If this element is not present in newList
// then add it
if (!newList.contains(element)) {
  
newList.add(element);
}
}
  
// return the new list
return newList;
}
//method to generate the all combination of numbers
public static void generate()
{
String fname;int i,j,a,b,c,sum=0;
//create two arraylists
ArrayList<Integer> alist=new ArrayList<Integer>();
ArrayList<Integer> alist1=new ArrayList<Integer>();
//create scanner object
Scanner scan = new Scanner(System.in);
  
/* enter filename with extension to open and read its content */
  
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
  
/* this will reference only one line at a time */
  
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
  
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
  
while((line = bufferedReader.readLine()) != null)
{
//add the elements into arraylist
       alist.add(Integer.parseInt(line));
}
//close the file
bufferedReader.close();
//add 0 as first element into alist1
alist1.add(0);
//add all elements into the alist1
for (i = 0; i < alist.size();i++)
   {
           sum=sum+(int)alist.get(i);//find the sum      
   alist1.add(alist.get(i));      
   }
//compute the combinations with all elements of alist
for (i = 0; i < alist.size();i++)
   {
for(j=i+1;j<alist.size();j++)
{
a=(int)(alist.get(i));

b=(int)(alist.get(j));
c=a+b;
alist1.add(c);//add the combinations to alist1

}       
   }
alist1.add(sum); //add the sum of all elements into alist1

// Remove duplicate elements if any
ArrayList<Integer>
newList = removeDuplicates(alist1);
System.out.println(newList); //display the new list as the result
}

catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}

public static void main(String[] input)
{
generate(); //call to the method
}
}

OUTPUT


Related Solutions

C++ Write a program that reads candidate names and numbers of votes in from a file....
C++ Write a program that reads candidate names and numbers of votes in from a file. You may assume that each candidate has a single word first name and a single word last name (although you do not have to make this assumption). Your program should read the candidates and the number of votes received into one or more dynamically allocated arrays. In order to allocate the arrays you will need to know the number of records in the file....
1. Write a function named “Number” that reads in a list of numbers until the user...
1. Write a function named “Number” that reads in a list of numbers until the user enters 0. It will return true if the user has entered more even numbers than odd numbers; otherwise it returns false. 2. Write a code segment to sort an array of students in ascending order of their IDs. Assume the array has been filled with names and assume the following declaration: struct Student { string name; int ID; } Student roster[30]; // Code to...
Implement in Python a script that does the following: 1) reads input from a supposed file...
Implement in Python a script that does the following: 1) reads input from a supposed file called firstnames_2.txt. 2) processes the input and writes and saves the output to a file. NOTE: Please make sure that the names are written in the outfile with one name on each line no comma ( , ) after the name in the output
Write a C++ function called parse that reads one line of user input from the keyboard...
Write a C++ function called parse that reads one line of user input from the keyboard and creates an array of the strings found in the input.  Your function should be passed the array and a reference variable that is to be assigned the length of the array.  Prompt the user and read the input from within the function. For example:  If the user inputs copy this that, the resulting array would have length 3 and contain the strings “copy”, “this”, and “that”....
Write a program in c that reads the content from the file and stores each line...
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation). For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int): 10067 26789 6789 3467
Write a parameterized function that takes in a file name as a parameter, reads the file,...
Write a parameterized function that takes in a file name as a parameter, reads the file, calculates the factorial of each number, and displays a formatted output as follows: Factorial of 10 = 3628800 Factorial of 5 = 120
Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using Notepad) into a one-dimensional array and then analyzes the numbers as described below. Your program must use loops to read the numbers into the array and to analyze the contents of the array. The program’s main function should do the following:  Read eight floating-point numbers from the file named numbers.txt into a onedimensional array, displaying each number on the screen.  Pass the...
Write a .m function file on MATLAB that reads the parameters stored in the file missile...
Write a .m function file on MATLAB that reads the parameters stored in the file missile data.txt into MATLAB. The function should have the following declaration: function [X0, Y0, Z0, m0, mf, Thmag0, theta, phi, Tburn] = read input( input filename, M id) where input filename is a string variable denoting the name of the file to be read and M_id is an integer which denotes the missile ID. The outputs are the initial position (X0, Y0, Z0), initial and...
Write a Python program that reads a file, input by the user, containing one word/token per...
Write a Python program that reads a file, input by the user, containing one word/token per line with an empty line between sentences. The program prints out the longest word found in the file along with its length.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT