Skip to content

Instantly share code, notes, and snippets.

@ZacharyJacobCollins
Last active October 13, 2016 17:58
Show Gist options
  • Save ZacharyJacobCollins/c05b4dce4a85f9f46bed9d6558607139 to your computer and use it in GitHub Desktop.
Save ZacharyJacobCollins/c05b4dce4a85f9f46bed9d6558607139 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Scanner;
//Zachary Collins
//100% Vegetarian Code
public class One {
//The main class
public static void main(String[] args) {
//Collect user input for n
int n = input();
ArrayList<Integer> list = count(n);
generateSubsets(list);
}
/**
* Given an n, returns an array list containing each number as an element up to n
* @param int n
* @return ArrayList arr
*
*/
private static ArrayList<Integer> count(int n) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i<=n; i++) {
list.add(i);
}
return list;
}
/**
* Generate and print all subsets possible given an integer
* @param an integer list containing teh numbers up to the given n input
*
*/
private static void generateSubsets(ArrayList<Integer> list)
{
//Start keeping track of how long the algorithm takes
long startTime = System.currentTimeMillis();
ArrayList<Integer> retList = new ArrayList<Integer>();
//<< shifts to left >> shifts to right
int subsets = 1 << list.size();
for(int i = 0; i < subsets; i++) {
int pos = list.size() - 1;
int mask = i;
while(mask > 0) {
if((mask & 1) == 1)
retList.add(list.get(pos));
//n two to the right
mask >>= 1;
pos--;
}
//replace the [ , ] in the arraylist with set notation, print
System.out.println(retList.toString()
.replace('[', '{')
.replace(']', '}')
);
//clear list in prep for more additions
retList.clear();
}
//Print out the elapsed time of the algorithm
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Runtime: " + elapsedTime + " ms");
}
/**
* Collect user input for n
* @return int n
*
*/
private static int input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value for n ");
return input.nextInt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment