Question

Write a program that will read a list of numbers and a desired sum, then determine...

Write a program that will read a list of numbers and a desired sum, then determine the subset of numbers in the list that yield that sum if such a subset exists. Answer from Data Structures (2nd Edition) Using JAVA Chapter 5.6, Problem 6PP: Does not fully answer the question. Specifically, ". . . then determine the subset of numbers in the list that yield that sum if such a subset exists" is not answered in provided solution. It should show the actual subsets that can be made to add up to the sum. Additionally, the text book is for "Using JAVA" and it should use Recursion since it is in Chapter 5, so the answer needs to be written in JAVA using RECURSION. And the display needs to state the number of subsets and then list the individual subsets.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class SubsetOfSum {

    // Data Fields
    /** The set of entered numbers */
    private static ArrayList<Integer> numbers;
    /** The desired sum */
    private static int sum;
    /** The list of all subsets whose elements sum to desired sum */
    private static ArrayList<ArrayList<Integer>> allSubsets = new ArrayList<ArrayList<Integer>>();
    /** Whether a subset was found */
    private static boolean found = false;

    /**
     * Call methods to get list of numbers and desired sum from user, then call
     * methods to find and print all subsets of the list whose elements total the sum.
     *
     * @param args
     */
    public static void main(String[] args) {
        getNumbers();
        getSum();

        findSubsets(numbers, 0);
        if (found) {
            printSubsets(allSubsets);
        } else {
            System.out.println("\nNo subsets sum to " + sum);
        }
    }

    /**
     * Prompt user for list of integers and store them in numbers ArrayList.
     */
    public static void getNumbers() {

        numbers = new ArrayList<Integer>();
        Scanner keyboard = new Scanner(System.in);

        System.out
                .println("Input list of integers. Press 'Enter' when finished: ");
        String numStr = keyboard.nextLine();

        StringTokenizer strToke = new StringTokenizer(numStr);

        while (strToke.hasMoreTokens()) {
            String token = strToke.nextToken();

            try { // Parse integers from user input and add to numbers
                numbers.add(Integer.parseInt(token));
            } catch (NumberFormatException e) {
                // If token is not an integer, it is not added to numbers
            }
        }
    }

    /**
     * Prompt user for desired sum and store it in sum.
     */
    public static void getSum() {

        Scanner keyboard = new Scanner(System.in);

        while (true) {
            try {
                System.out.print("Input desired sum: ");
                sum = keyboard.nextInt();
                break;
            } catch (InputMismatchException e) {
                // If user inputs something other than an int, they are prompted
                // to try again
                System.out.println("Error: Invalid entry. Please input an integer.");
                keyboard.nextLine();
            }
        }
    }

    /**
     * Recursively search through every subset of a given set. If the elements
     * of a subset sum to desired sum, it is added to the allSubsets list.
     *
     * @param set
     *            The set to be searched
     * @param i
     *            The index of the current element being examined
     */
    public static void findSubsets(ArrayList<Integer> set, int i) {

        if (sum == sumOfSet(set)) { // Base Case: success
            addSubset(set);
            found = true;
            return;
        } else if (set.isEmpty() || i == set.size()) { // Base Case: failure
            return;
        } else { // Recursive Cases

            // Create a new subset without element at index i
            ArrayList<Integer> newSet = new ArrayList<Integer>(set);
            newSet.remove(i);

            findSubsets(set, i + 1); // test subsets with element i included
            findSubsets(newSet, i); // test subsets without element i
        }
    }

    /**
     * Store the current subset into allSubsets. If allSubsets already contains
     * current subset, it is not added.
     *
     * @param newSet
     *            The subset to be added.
     */
    public static void addSubset(ArrayList<Integer> newSet) {
        for (ArrayList<Integer> subset : allSubsets) {
            if (newSet.equals(subset)) {
                return;
            }
        }
        allSubsets.add(newSet);
    }

    /**
     * Return the sum of all elements in a given set.
     *
     * @param set
     *            The set whose elements are to be summed
     * @return The sum of the set
     */
    public static int sumOfSet(ArrayList<Integer> set) {

        int theSum = 0;
        for (int i : set) {
            theSum += i;
        }
        return theSum;
    }

    /**
     * Output all subsets in a given list.
     *
     * @param sets
     *            The list of subsets
     */
    private static void printSubsets(ArrayList<ArrayList<Integer>> sets) {

        System.out.println("\nSubsets that sum to " + sum + ":");

        for (ArrayList<Integer> set : sets) {
            System.out.println(set.toString()); // print in [a, b, c, ...] format
        }
    }
}


Add a comment
Know the answer?
Add Answer to:
Write a program that will read a list of numbers and a desired sum, then determine...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that will read a list of numbers and a desired sum, then determine...

    Write a program that will read a list of numbers and a desired sum, then determine the subset of numbers in the list that yield that sum if such a subset exists. Answer from Data Structures (2nd Edition) Chapter 5.6, Problem 6PP: Does not fully answer the question. Specifically, ". . . then determine the subset of numbers in the list that yield that sum if such a subset exists" is not answered in provided solution. It should show the...

  • Write a program that will read a list of numbers and a desired sum, then determine the subset of ...

    Write a program that will read a list of numbers and a desired sum, then determine the subset of numbers in the list that yield that sum if such a subset exists. Answer from Data Structures (2nd Edition) Chapter 5.6, Problem 6PP: Does not fully answer the question. Specifically, ". . . then determine the subset of numbers in the list that yield that sum if such a subset exists" is not answered in provided solution. It should show the...

  • Write a Java program called EqualSubsets that reads a text file, in.txt, that contains a list...

    Write a Java program called EqualSubsets that reads a text file, in.txt, that contains a list of positive and negative integers (duplicates are possible) separated by spaces and/or line breaks. Zero may be included. After reading the integers, the program saves them in a singly linked list in the same order in which they appear in the input file. Then, without changing the linked list, the program should print whether there exists two subsets of the list whose sums are...

  • Write a python program that generates a list of 50 random numbers. The program should display...

    Write a python program that generates a list of 50 random numbers. The program should display (with labels) the sum, average, largest, and smallest of the list along with the list before and after sorting. Bonus: Find the mode (if any)

  • Write a program that can: 1. Insert twenty random numbers into a linked list. The numbers...

    Write a program that can: 1. Insert twenty random numbers into a linked list. The numbers should be within a range (E.g., 1 to 7). The user should be prompted to enter the minimum number and maximum number of the range. Each number should be inserted at the end of the list. Section 7.8 of the textbook covers the random number generator. Examples of how to use the random number generator are in Fig 7.6 and 7.7. Here is a...

  • Data Structures(2nd Edition Using JAVA Chapter Review, Problem 6PP does not provide an answer: "T...

    Data Structures(2nd Edition Using JAVA Chapter Review, Problem 6PP does not provide an answer: "The Problem Statement is as follows": In a breadth-first traversal of a binary tree, the nodes are visited in an order prescribed by their level. First visit the node at level 1, the root node. Then visit the nodes at level 2, in left-to-right order, and so on. You can use a queue to implement a breadth-first traversal of a binary tree". Algorithm for Breath-First Traversal...

  • Data Structures(2nd Edition Using JAVA Chapter Review, Problem 6PP does not provide an answer: "The Problem...

    Data Structures(2nd Edition Using JAVA Chapter Review, Problem 6PP does not provide an answer: "The Problem Statement is as follows": In a breadth-first traversal of a binary tree, the nodes are visited in an order prescribed by their level. First visit the node at level 1, the root node. Then visit the nodes at level 2, in left-to-right order, and so on. You can use a queue to implement a breadth-first traversal of a binary tree". Algorithm for Breath-First Traversal...

  • mathTutor Write a program that selects two random numbers -20 to 20. The two numbers would...

    mathTutor Write a program that selects two random numbers -20 to 20. The two numbers would get displayed with "+" between them. The user should enter the sum of the two numbers. The program should print "Incorrect" if the user enters a wrong answer and re-prompts the user to re-enter the answer again. Limit the number of incorrect tries to 3. After 3 incorrect tries print the correct answer. The program should print a message like "Correct!" if the user...

  • Create a program that will determine the even number(s) from a list of numbers. Your program...

    Create a program that will determine the even number(s) from a list of numbers. Your program should create and call a function FindEven that accepts a list of numbers and returns a list of only the even numbers in sorted order. Note that the original list is given in the starter code. def body(): numberlist = [1, 1000, 5, -3, 2, 16 # Write your code here and notice level # Do NOT include: if __name__ == been provided for...

  • Java: The local Driver's License Office has asked you to write a program that grades the...

    Java: The local Driver's License Office has asked you to write a program that grades the written portion of the driver's   license exam. The exam has 20 multiple choice questions.   Here are the correct answers:    1. B  6. A  11.B  16. C    2. D  7. B  12.C  17. C    3. A   8. A  13.D  18. B    4. A  9. C  14.A  19. D    5. C  10. D  15.D  20. A    Your program should store the correct answers in an array. (Store each question's answer in an element of a String array.) The program...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT