Question

Course: Data Structures and Algorithms, in Java Implement a function that reads numbers in from a...

Course: Data Structures and Algorithms, in Java

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 allSums( ArrayList arr ) { ... }

Homework Answers

Answer #1

/******************************SumOfSubset.java*******************/

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class SumOfSubset {

   static ArrayList<Integer> allSum;

   public static void main(String[] args) {

       ArrayList<Integer> numbers = new ArrayList<>();
       File file = new File("number.txt");

       //read integers form file
       try {

           Scanner sc = new Scanner(file);
           // while loop till file has line
           while (sc.hasNextLine()) {

               numbers.add(Integer.parseInt(sc.nextLine()));
           }
           sc.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       //calling method
       ArrayList<Integer> allSum = allSums(numbers);
       System.out.println(allSum);
   }

   public static ArrayList<Integer> allSums(ArrayList<Integer> numbers) {

       allSum = new ArrayList<>();
       //helper method
       getSum(numbers, 0, 0);
       //remove the duplicates
       Set<Integer> set = new HashSet<>(allSum);
       allSum.clear();
       allSum.addAll(set);
       return allSum;
   }

   private static void getSum(ArrayList<Integer> numbers, int starting, int sum) {

       if (numbers.size() == starting) {
           allSum.add(sum);
           return;
       }
       int value = sum + numbers.get(starting);
       getSum(numbers, starting + 1, value);
       getSum(numbers, starting + 1, sum);

   }

}
/*******************output*******************/

[0, 1, 2, 3, 4, 5, 6, 7]

[0, 2, 4, 6, 9, 11, 13, 15]

numbers.txt

Please let me know if you have any doubt or modify the answer, Thanks :)

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Data structures in java Implement the following classes: 1. class Course that includes three instance variables:...
Data structures in java Implement the following classes: 1. class Course that includes three instance variables: private String Name; // the course name private int ID; // the course ID private Course next; // the link Your class should have the following:  A constructor that initializes the two instance variables id and name.  Set and get methods for each instance variable. 2. class Department that includes three instance variables: private String deptName; private Course head, tail; Your class...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
java 8.1: Frequency Design and implement an application that reads an arbitrary number of integers that...
java 8.1: Frequency Design and implement an application that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. After all input has been processed, print all of the values (with the number of occurrences) that were entered one or more times. The output should be one frequency count per line with the following format: 3 occurrences of 2 7 occurrences of 5 SPECIFICATION OF NAMES:...
Use C++ Write a program that first reads in how many whole numbers the user wants...
Use C++ Write a program that first reads in how many whole numbers the user wants to sum, then reads in that many whole numbers, and finally outputs the sum of all the numbers greater than zero, the sum of all the numbers less than zero (which will be a negative number or zero), and the sum of all the numbers, whether positive, negative, or zero. The user enters the numbers just once each and the user can enter them...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with the default values denoted by dataType name : defaultValue - String animal : empty string - int lapsRan : 0 - boolean resting : false - boolean eating : false - double energy : 100.00 For the animal property implement both getter/setter methods. For all other properties implement ONLY a getter method Now implement the following constructors: 1. Constructor 1 – accepts a String...
This is a java assignment on repl.it my code works but I keep failing the tests....
This is a java assignment on repl.it my code works but I keep failing the tests. Can anyone help me Write the body of the fileAverage() method. Have it open the file specified by the parameter, read in all of the floating point numbers in the file and return their average (rounded to 1 decimal place) For the testing system to work, don't change the class name nor the method name. Furthermore, you cannot add "throws IOException" to the fileAverage()...
Using Java, please implement the Poker and PokerHand classes to provide the expected output using the...
Using Java, please implement the Poker and PokerHand classes to provide the expected output using the CardDemo class. Rules are the following: - Deck and PockerHand should be Iterable (note that you may just reuse one of the underlying iterators to provide this functionality) - Poker should implement 2 methods checking for two possible poker hands , see the comments inside the classes for details. Hint: remember how one can count the frequency of words in text? - whenever you...
For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from...
For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from a file. Specifically, you will implement the following function: /* * Reads one arithmetic "expression" at a time from a file stream, computes, then * returns the result. If there are additional expressions in the file, they are * read and computed by successive calls to “calculator”. * * “Expressions” are groups of operations (add, subtract, multiply, divide). Your * calculator will read and...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT