Future Vision BIE Future Vision BIE


ONE STOP FOR ALL STUDY MATERIALS & LAB PROGRAMS


E MENU Whatsapp Share Join Telegram, to get Instant Updates
× NOTE! Click on MENU to Browse between Subjects...

Advertisement

DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY

(Effective from the academic year 2018 -2019)

SEMESTER - IV

Course Code 18CSL47

CIE Marks 40

Number of Contact Hours/Week 0:2:2

SEE Marks 60

Total Number of Lab Contact Hours 36

Exam Hours 03



Experiments 1A

Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution.


Advertisement


Advertisement

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Scanner;

class Subset {
    static int[] arr;
    static int count;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter n value");
        int n = scan.nextInt();
        arr = new int[n];

        System.out.println("Enter Elements of Set");
        for (int i = 0; i < n; i++) {
            arr[i] = scan.nextInt();
        }

        System.out.println("Enter Total Sum value");
        int total = scan.nextInt();
        scan.close();
        
        subSet(total, n - 1, new boolean[n]);

        if (count == 0) {
            System.out.println("No solution");
        }
    }

    static void subSet(int total, int index, boolean[] solution) {
        if (total == 0) {
            printSolution(solution);
        } else if (total < 0 || index < 0) {
            return;
        } else {
            boolean[] tempSolution = solution.clone();
            tempSolution[index] = false;
            subSet(total, index - 1, tempSolution);
            tempSolution[index] = true;
            subSet(total - arr[index], index - 1, tempSolution);
        }
    }

    static void printSolution(boolean[] solution) {
        count += 1;
        System.out.print("Solution: ");
        for (int i = 0; i < solution.length; i++) {
            if (solution[i]) {
                System.out.print(arr[i] + " ");
            }
        }
        System.out.println();
    }
}

Advertisement

output
Fig 11.1: Output .

Advertisement
output
Fig 11.2: Output .

× Note Please Share the website link with Your Friends and known Students...

-ADMIN

× Note Page Number is specified to navigate between Pages...
T = Text book
QB = Question Bank
AS = Amswer Script


-ADMIN

Advertisement