Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in Java that consists of a single file. Input should be read fro

ID: 3720234 • Letter: W

Question

Write a program in Java that consists of a single file. Input should be read from the terminal as a series of lines. The first input is a target integer. The second input: another integer that denotes the size of a set (let say K). And the following inputs are K lines , each containing a single integer (which combined= set {k1, ..., kK}). Determine if there exist a subset of {k1, ..., KS} that adds up to exactly the target. If this subset exists, print out s lines (s=size of subset) and each line=one element of the subset.

Explanation / Answer

here is your program : -------->>>>>>>>

import java.util.Scanner;

public class FindSubset{
public static boolean findSubset(int n,int[] set,int tar){
  int[] arr = new int[n];
  for(int i = 0;i<n;i++){
   arr[i] = i;
  }
  int sum = 0;
  int ss = n-1;
  while(arr[0] != n){
   sum = 0;
   for(int i = 0;i<n;i++){
    sum += set[arr[i]];
   }
   if(sum == tar){
    System.out.println("List Of "+n+" elements which adds up to give "+tar+" .");
    for(int i = 0;i<n;i++){
     System.out.println(set[arr[i]]+" ");
    }
    return true;
   }
   arr[n-1] = arr[n-1] + 1;
   if(arr[n-1] >= set.length){
    for(int i = 0;i<n-1;i++){
     arr[i] = arr[i] + 1;
    }
    ss = ss + 1;
    if(ss >= set.length){
     break;
    }
    arr[n-1] = ss;
   }
  }
  return false;
}
public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter Target Number : ");
  int target = sc.nextInt();
  System.out.println("Enter The size of set : ");
  int size = sc.nextInt();
  int[] set = new int[size];
  System.out.println("Enter the set element line by line : ");
  for(int i = 0;i<size;i++){
   set[i] = sc.nextInt();
  }
  int st = 0;
  for(int i = 1;i<=size;i++){
   if(findSubset(i,set,target)){
    st = 1;
    break;
   }
  }
  if(st == 0){
   System.out.println("No Subset Found which have the sum = "+target);
  }
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote