SlideShare a Scribd company logo
1 of 4
Download to read offline
Write a function which return a list of all of the n element subset of a given set
Implement in JAVA Question 3 Write a function that returns a list of all of the n-element subsets
of a given set. For example, if the given set is [1,2,3] and n is 2, then the returned list should
contain [1,2], [1,3], and [2,3]. The order of the elements is not important.
Solution
The program for this problem is as follows:
Comments are included in the program for explaining the steps.
A sample output is attached below the program.
package com.temp;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Program to find sublists of a list.
* @author Rohit Phatak
*
*/
public class subset {
/**
* This list will contain the resultant sublists.
*/
static List list = new ArrayList<>();
public static void main(String arg[]){
/**
* Input a list comma separated.
*/
System.out.println("Enter a list : ");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String[] sArr = s.split(",");
/**
* Input a value of n.
*/
System.out.println("Enter value of n : ");
Integer n = scanner.nextInt();
/**
* Check if value of n is greater than entered list.
*/
if(sArr.length < n){
System.out.println("Length of list is less than value of n");
} else if(sArr.length > 0){
getSubsetList(sArr,n);
System.out.println("List is as :");
/**
* Printing the sublists.
*/
for(String[] str : list){
String printVar = "";
for(String temps : str)
printVar+=temps+",";
System.out.println("["+printVar.substring(0, printVar.length()-1)+"]");
}
} else {
System.out.println("Please enter atleast one element:");
}
scanner.close();
}
/**
* This method calls the recursive function which is used to obtain the sublists.
* @param sArr
* @param n
* @return
*/
public static List getSubsetList(String[] sArr,Integer n){
List lista = new ArrayList<>();
sublist(sArr, 0, n, new String[n]);
return lista;
}
/**
* This is a recursive function.
* This function will iterate over itself for finding the sublist.
*
* Parameters are as follows:
*
* @param arr -> List entered by the user.
* @param n -> Value of sublist entered by user.
* @param startPosition -> index to start creating the sublist.
* @param result -> resultant sublist
*/
public static void sublist(String[] arr, int startPosition, int n, String[] result){
/**
* Check for the value of n ==0.
* If n==0 break from the recursion.
*/
if (n == 0){
/**
* Add the sublist 'result' in the list.
*/
list.add(result.clone());
return;
}
/**
* Iterate through for loop starting from startPosition till length of list minus entered value
n.
*/
for (int i = startPosition; i <= arr.length-n; i++){
/**
* Here result is a temporary sublist.
* This for loop adds an element to the temporary sublist in each iteration.
* The element is added from the complete list entered by user.
* Location of element is iTh index.
*/
result[result.length - n] = arr[i];
/**
* After adding the element to the temporary sublist, the sublist and the updated start and
end positions are recurssed to itself.
*/
sublist(arr, i+1, n-1, result);
}
}
}
Sample output of the above program :
Enter a list :
1,2,3,5
Enter value of n :
2
List is as :
[1,2]
[1,3]
[1,5]
[2,3]
[2,5]
[3,5]

More Related Content

Similar to Write a function which return a list of all of the n element subset .pdf

we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdf
gudduraza28
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
aioils
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdfLabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
ankit11134
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
Conint29
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdf
aggarwalopticalsco
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
maheshkumar12354
 
import java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdfimport java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdf
aquastore223
 
Help in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdfHelp in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdf
manjan6
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
stopgolook
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
callawaycorb73779
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
gopalk44
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 

Similar to Write a function which return a list of all of the n element subset .pdf (20)

Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdfUsing Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
 
we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdf
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docx
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdfLabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdf
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
 
import java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdfimport java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdf
 
Help in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdfHelp in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdf
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 

More from hardjasonoco14599

Which of the following is NOT a complication in development of an HIV.pdf
Which of the following is NOT a complication in development of an HIV.pdfWhich of the following is NOT a complication in development of an HIV.pdf
Which of the following is NOT a complication in development of an HIV.pdf
hardjasonoco14599
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
hardjasonoco14599
 
what does it takes to be a living organ What does it take to be a l.pdf
what does it takes to be a living organ What does it take to be a l.pdfwhat does it takes to be a living organ What does it take to be a l.pdf
what does it takes to be a living organ What does it take to be a l.pdf
hardjasonoco14599
 
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdfsafety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
hardjasonoco14599
 
Question 1 A ____________ is an intelligent device that controls the.pdf
Question 1 A ____________ is an intelligent device that controls the.pdfQuestion 1 A ____________ is an intelligent device that controls the.pdf
Question 1 A ____________ is an intelligent device that controls the.pdf
hardjasonoco14599
 
I finished most of the program, but having trouble with some key fea.pdf
I finished most of the program, but having trouble with some key fea.pdfI finished most of the program, but having trouble with some key fea.pdf
I finished most of the program, but having trouble with some key fea.pdf
hardjasonoco14599
 
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdfKevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
hardjasonoco14599
 

More from hardjasonoco14599 (20)

[Quantum Mechanics] In my class we are talking about the quantum har.pdf
[Quantum Mechanics] In my class we are talking about the quantum har.pdf[Quantum Mechanics] In my class we are talking about the quantum har.pdf
[Quantum Mechanics] In my class we are talking about the quantum har.pdf
 
what is tax preferenceSolutionTax preferences are measures of .pdf
what is tax preferenceSolutionTax preferences are measures of .pdfwhat is tax preferenceSolutionTax preferences are measures of .pdf
what is tax preferenceSolutionTax preferences are measures of .pdf
 
Which of the following is true regarding homologous structuresA. .pdf
Which of the following is true regarding homologous structuresA. .pdfWhich of the following is true regarding homologous structuresA. .pdf
Which of the following is true regarding homologous structuresA. .pdf
 
Why is it reasonable to assume that Venus, Earth, and Mars started w.pdf
Why is it reasonable to assume that Venus, Earth, and Mars started w.pdfWhy is it reasonable to assume that Venus, Earth, and Mars started w.pdf
Why is it reasonable to assume that Venus, Earth, and Mars started w.pdf
 
Which of the following is NOT a complication in development of an HIV.pdf
Which of the following is NOT a complication in development of an HIV.pdfWhich of the following is NOT a complication in development of an HIV.pdf
Which of the following is NOT a complication in development of an HIV.pdf
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
 
Which of the following groups is responsible for the actual developm.pdf
Which of the following groups is responsible for the actual developm.pdfWhich of the following groups is responsible for the actual developm.pdf
Which of the following groups is responsible for the actual developm.pdf
 
Whats the role of the gastric caeca in a grasshopperSolutionGr.pdf
Whats the role of the gastric caeca in a grasshopperSolutionGr.pdfWhats the role of the gastric caeca in a grasshopperSolutionGr.pdf
Whats the role of the gastric caeca in a grasshopperSolutionGr.pdf
 
what does it takes to be a living organ What does it take to be a l.pdf
what does it takes to be a living organ What does it take to be a l.pdfwhat does it takes to be a living organ What does it take to be a l.pdf
what does it takes to be a living organ What does it take to be a l.pdf
 
ve targets. ball and sodket hinge joint condyloid joint saddle jo.pdf
ve targets. ball and sodket hinge joint condyloid joint saddle jo.pdfve targets. ball and sodket hinge joint condyloid joint saddle jo.pdf
ve targets. ball and sodket hinge joint condyloid joint saddle jo.pdf
 
This one is for you - assume that this pedigree shows the inheritance.pdf
This one is for you - assume that this pedigree shows the inheritance.pdfThis one is for you - assume that this pedigree shows the inheritance.pdf
This one is for you - assume that this pedigree shows the inheritance.pdf
 
There are 7 people in the elevator in a 10-story building. They are .pdf
There are 7 people in the elevator in a 10-story building. They are .pdfThere are 7 people in the elevator in a 10-story building. They are .pdf
There are 7 people in the elevator in a 10-story building. They are .pdf
 
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdfsafety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
safety Construction Safety-Quiz 1 According to OSHA, what must man.pdf
 
Question 1 A ____________ is an intelligent device that controls the.pdf
Question 1 A ____________ is an intelligent device that controls the.pdfQuestion 1 A ____________ is an intelligent device that controls the.pdf
Question 1 A ____________ is an intelligent device that controls the.pdf
 
I finished most of the program, but having trouble with some key fea.pdf
I finished most of the program, but having trouble with some key fea.pdfI finished most of the program, but having trouble with some key fea.pdf
I finished most of the program, but having trouble with some key fea.pdf
 
In sliding window protocol the left wall of the sender sliding winod.pdf
In sliding window protocol the left wall of the sender sliding winod.pdfIn sliding window protocol the left wall of the sender sliding winod.pdf
In sliding window protocol the left wall of the sender sliding winod.pdf
 
In mice, the black allele (B) is dominant to the recessive white all.pdf
In mice, the black allele (B) is dominant to the recessive white all.pdfIn mice, the black allele (B) is dominant to the recessive white all.pdf
In mice, the black allele (B) is dominant to the recessive white all.pdf
 
How will the rate of diffusion of an interstitial i Impurity atom Inc.pdf
How will the rate of diffusion of an interstitial i Impurity atom Inc.pdfHow will the rate of diffusion of an interstitial i Impurity atom Inc.pdf
How will the rate of diffusion of an interstitial i Impurity atom Inc.pdf
 
Let R be an integral domain. Prove 1R and -1R are the only units of .pdf
Let R be an integral domain. Prove 1R and -1R are the only units of .pdfLet R be an integral domain. Prove 1R and -1R are the only units of .pdf
Let R be an integral domain. Prove 1R and -1R are the only units of .pdf
 
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdfKevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
Kevin Keller’s aunt’s husband and his girl cousin have died of heart.pdf
 

Recently uploaded

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Recently uploaded (20)

PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Write a function which return a list of all of the n element subset .pdf

  • 1. Write a function which return a list of all of the n element subset of a given set Implement in JAVA Question 3 Write a function that returns a list of all of the n-element subsets of a given set. For example, if the given set is [1,2,3] and n is 2, then the returned list should contain [1,2], [1,3], and [2,3]. The order of the elements is not important. Solution The program for this problem is as follows: Comments are included in the program for explaining the steps. A sample output is attached below the program. package com.temp; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Program to find sublists of a list. * @author Rohit Phatak * */ public class subset { /** * This list will contain the resultant sublists. */ static List list = new ArrayList<>(); public static void main(String arg[]){ /** * Input a list comma separated. */ System.out.println("Enter a list : "); Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); String[] sArr = s.split(","); /** * Input a value of n.
  • 2. */ System.out.println("Enter value of n : "); Integer n = scanner.nextInt(); /** * Check if value of n is greater than entered list. */ if(sArr.length < n){ System.out.println("Length of list is less than value of n"); } else if(sArr.length > 0){ getSubsetList(sArr,n); System.out.println("List is as :"); /** * Printing the sublists. */ for(String[] str : list){ String printVar = ""; for(String temps : str) printVar+=temps+","; System.out.println("["+printVar.substring(0, printVar.length()-1)+"]"); } } else { System.out.println("Please enter atleast one element:"); } scanner.close(); } /** * This method calls the recursive function which is used to obtain the sublists. * @param sArr * @param n * @return */ public static List getSubsetList(String[] sArr,Integer n){ List lista = new ArrayList<>(); sublist(sArr, 0, n, new String[n]); return lista; }
  • 3. /** * This is a recursive function. * This function will iterate over itself for finding the sublist. * * Parameters are as follows: * * @param arr -> List entered by the user. * @param n -> Value of sublist entered by user. * @param startPosition -> index to start creating the sublist. * @param result -> resultant sublist */ public static void sublist(String[] arr, int startPosition, int n, String[] result){ /** * Check for the value of n ==0. * If n==0 break from the recursion. */ if (n == 0){ /** * Add the sublist 'result' in the list. */ list.add(result.clone()); return; } /** * Iterate through for loop starting from startPosition till length of list minus entered value n. */ for (int i = startPosition; i <= arr.length-n; i++){ /** * Here result is a temporary sublist. * This for loop adds an element to the temporary sublist in each iteration. * The element is added from the complete list entered by user. * Location of element is iTh index. */ result[result.length - n] = arr[i]; /**
  • 4. * After adding the element to the temporary sublist, the sublist and the updated start and end positions are recurssed to itself. */ sublist(arr, i+1, n-1, result); } } } Sample output of the above program : Enter a list : 1,2,3,5 Enter value of n : 2 List is as : [1,2] [1,3] [1,5] [2,3] [2,5] [3,5]