Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.
Hello everyone.
I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.
What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.
What i tried was this:
public class ItemSet
{
public static void main(String []args)
{
int[] itemSet;
itemSet = new int[5];
itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
itemSet[1] = 0;
itemSet[2] = 0;
itemSet[3] = 0;
itemSet[4] = 0;
int count = 1;
int assignItem = 0;
int countTwo = 1;
while (count > 5) {
while (countTwo == 1) {
assignItem = (int)(Math.random()*76);
// here is where i get totally lost
if (assignItem.compareTo(itemSet)) {
countTwo = 1;
} else {
itemSet[(count--)] = assignItem;
countTwo = 0;
}
}
count = count++;
}
}
}
Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx
Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.
You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
}
}
}
To print the values stored in the array, try using an enhanced-for loop:
for (int element : itemSet) {
System.out.println(element);
}
To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:
import java.util.Arrays; // you need this to use Arrays.toString()
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
for (int j = i - 1; j >= 0; j--) {
if (itemSet[j] == itemSet[i]) {
System.out.println("Comparing " + itemSet[j] +
" and " + itemSet[i]);
i--;
break; // not really needed but illustrates a way to exit a loop immediately
}
}
}
// this is a handy way to print all the data in an array quickly
System.out.println(Arrays.toString(itemSet));
}
}
public static void main (String[] args){
//you dont need to initialize the array with zeros
int[] itemSet = new int[5];
int counter = 0;
while(counter < itemSet.length){
int random = (int)(Math.random() * 76);
//checks if the array already contains the random number
if(!Arrays.asList(itemSet).contains(random)){
itemSet[counter] = random;
counter++;
}
}
//print the array
for(int i : itemSet) System.out.println(i);
}
There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:
public static void main(String[] args) {
int[] itemSet;
itemSet = new int[5];
int assignItem;
for (int i = 0; i < 5; i++) {
assignItem = (int)(Math.random()*76);
if(!duplicate(assignItem,itemSet,i)){
itemSet[i] = assignItem;
}
}
}
private static boolean duplicate(int assignItem, int[] itemSet, int i) {
for (int j = 0; j < i; j++) {
if (assignItem == itemSet[j])
return true;
}
return false;
}
The most straight forward way would be checking through the array for existing value before inserting the current random value.
Generate a random value
Check if value exists in array
If already exist in array, generate another value
If not exist in array, set value to current element
In codes:
public static void main(String[] args){
int idx = 0;
int[] myArray = new int[5];
Random rnd = new Random();
int val = rnd.nextInt(76);
do{
if(numExistInArray(val, myArray))
val = rnd.nextInt(76); //if val exist in array, generate another number
else
myArray[idx++] = val; //if val not exist in array, fill array
}while(idx != myArray.length); //do not exit loop till all numbers are filled
}
public static boolean numExistInArray(int val, int[] array){
for(int x=0; x<array.length; x++)
if(array[x] == val)
return true;
return false;
}
I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:
for (int count = 0; count < 5 ; count++) {
assignItem = (int)(Math.random()*76);
if (assignItem==itemSet[count]&&itemSet[count]!=0) {
//If true do this
}
else {
itemSet[count] = assignItem;
}
}
Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.
If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:
public static void main(String[] args) {
List<Integer> unusedNumbers = new ArrayList();
// Populate list with values
for (int i = 0; i <= 75; i++) unusedNumbers.add(i);
int[] itemSet = new int[5];
for (int i = 0; i < 5; i++) {
int randomIndex = (int) (Math.random() * unusedNumbers.size());
int randomInt = unusedNumbers.remove(randomIndex);
itemSet[i] = randomInt;
}
}
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
I am trying to program a Java Code in which, given the lenght of an int array and a min and max values it returns an random array values.
I am trying to program it in the most simple way, but I am still not getting how the programming process works.
What I have tried is the following:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
System.out.println(createRandom(10));
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt();
while (array[i] > min) ;
while (array[i] < max) ;
}
return array;
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 10;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max-min+1) + min;
System.out.print(array[i] +" ");
}
return array;
}
public static void main(String[] args){
createRandom(5);
}
Try using IntStream to achieve what you want
public static void main(String[] args) {
int[] arr = createRandom(10);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static int[] createRandom(int n) {
Random r = new Random();
int min = 5;
int max = 99;
return IntStream
.generate(() -> r.nextInt(max - min) + min)
.limit(n)
.toArray();
}
The first thing we must adjust is the random number generation. It appears you specify a min and max, so a number must be generated in with these bounds. We can use the Random.nextInt(int bound) method to set a range equal to max - min. However, this range will start from 0, so we must add your min value to make the bound complete. Using this process will eliminate the need for the existing while loops. See this question for more on this.
Now, every value in the array will be generated as
array[i] = rd.nextInt(max - min) + min
When trying to print array elements, a System.out.println() statement with the variable name of the array will print a memory address of the array. This will NOT print the entire array of values.
We must instead iterate over the elements to print them. It would be best to use a for loop to do this, but your program could generate an array of any size. So, we should use a for-each loop instead as follows:
for (int num : createRandom(10)) {
System.out.println(num);
}
This for-each is saying "for each int in the array returned by createRandom(10), refer to is as variable num and print it."
This is the final code:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
for (int num : createRandom(10)) {
System.out.println(num);
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max - min) + min;
System.out.println(array[i]);
}
return array;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
. Basically what the following code does (suppose to) is, create a set of non-repeating random numbers, fill them up to an array which gets converted to a list, and sort them out. The problem is the nested for loops, i managed a work around but not even sure how it works. Secondely, i cant seem to sort it correctly, things repeat and out of bound errors pop up from time to time.
How the code works:
Generate non-repeating random numbers
Fill an array with them
Use nested for loop to find the smallest value
Insert that to a new array
Remove it from the first array
Repeat last 2 steps till the first array is empty and second array
os filled in a sorted order
import org.apache.commons.lang.ArrayUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Sorter {
public static void main(String[] args) {
int[] process = fillArray(20,1,25);
sorter(process,20);
}
public static int[] sorter(int array[],int size) {
int[] useArray = array;
Integer[] newArray = ArrayUtils.toObject(useArray);
List<Integer> arrayList = new ArrayList(Arrays.asList(newArray));
//System.out.println((arrayList));
int counter = 1;
int minval = 0;
int diffsize = size - 1;
int actualVal = 0;
int storeArray[] = new int[size];
int removeIndex =0;
Integer[] newStore = ArrayUtils.toObject(storeArray);
List<Integer> storeList = new ArrayList(Arrays.asList(newStore));
System.out.println((arrayList));
// Both loops messed up
for (int i = 0; i < size+diffsize; i++) {
for (int n = 0; n < size-1; n++) {
if (arrayList.get(minval) < arrayList.get(counter)) {
actualVal = arrayList.get(minval);
System.out.println((arrayList.get(minval)) + " Less than " + arrayList.get(counter));
counter = counter + 1;
removeIndex = minval;
} else {
actualVal = arrayList.get(counter);
System.out.println((arrayList.get(counter)) + " Less than " + arrayList.get(minval));
minval = counter;
counter = counter + 1;
removeIndex = counter;
}
}
// System.out.println(actualVal);
storeList.add(actualVal);
arrayList.remove(actualVal); // need to remove the smallest value to repeat the sorting and get the next smallest value, but this is not removing it
size = size - 1;
counter = 1;
minval = 0;
// if (i + size == i) {
// storeList.set(i, arrayList.get(0));
// }
// System.out.println(removeIndex);
// System.out.println(arrayList);
}
// System.out.println(storeList);
int[] ints = new int[storeList.size()];
int d = 0;
for (Integer u : storeList) {
ints[d++] = u;
}
return ints;
}
public static int randomNum(int lower,int upper){
Random rand = new Random();
int randomNum = lower + rand.nextInt((upper- lower) + 1);
return randomNum;
}
public static int[] fillArray(int size,int lowerBound,int upperBound){
int holdArray[] = new int[size];
int rand = 0;
for (int count =0;count < holdArray.length;count++){
holdArray[count] = 0;
}
for (int count =0;count < holdArray.length;count++){
rand = randomNum(lowerBound,upperBound);
if (ArrayUtils.contains(holdArray, rand)) {
while (ArrayUtils.contains(holdArray, rand)) {
rand = randomNum(0, 20);
}
}
holdArray[count] = rand;
}
// System.out.println(Arrays.toString(holdArray));
//return holdArray;
return holdArray;
}
}
Can you give a compelling reason to justify in converting from array to list? why not use only list or only array altogether? I use ArrayList in my answer below;
First of, the fillArray class. You do not need to fill with all zeros. Why even bother to fill it with a value that you will replace anyway?
public static ArrayList<Integer> fillArray(int size,int lowerBound,int upperBound){
ArrayList<Integer> a = new ArrayList<Integer>(size);
for (int count =0;count < size;count++){
Integer rand = new Integer(randomNum(lowerBound,upperBound));
a.add(rand);
}
return a;
}
Second, the sorting class. Your method as you said, searching for lowest value then do magic stuff and what not.
public static ArrayList<Integer> sorter(ArrayList<Integer> unsorted) {
ArrayList<Integer> sortedArray = new ArrayList<Integer>(unsorted.size());
while(!unsorted.isEmpty()) { //repeats until the unsorted list is empty
int minval = unsorted.get(0);
int removeIndex = 0;
for(int i=1;i<unsorted.size();i++)
if (unsorted.get(i)<minval) {
minval = unsorted.get(i);
removeIndex = i;
}
sortedArray.add(minval);
unsorted.remove(removeIndex);
}
return sortedArray;
}
main method to test it
public static void main(String[] args) {
ArrayList<Integer> a = fillArray(20,1,25);
System.out.println("unsorted array");
for (Integer c : a)
System.out.print(c + ";");
ArrayList<Integer> b = sorter(a);
System.out.println("\nnew unsorted array");
for (Integer c : a)
System.out.print(c + ";");
System.out.println("\nsorted array");
for (Integer c : b)
System.out.print(c + ";");
}
this outputs
unsorted array
22;2;23;22;13;12;4;1;7;14;25;18;9;12;3;8;20;3;1;20;
new unsorted array
sorted array
1;1;2;3;3;4;7;8;9;12;12;13;14;18;20;20;22;22;23;25;
Separate out the "find the smallest" and "insertion/deletion" from arrays into two methods and then use them.
This way the code will be more manageable. Below is a sample find_min method.
int find_min(int[] array, int start) {
int min = Integer.MAX_VALUE;
for(int i = start; i < array.length; ++i)
if(array[i] < min)
min = array[i] ;
return min;
}
Now in the sorting routine, use the find_min to find the minimum element and insert it to new array and then delete the minimum element from the original array. However, this method does not return the index of the minimum element. So, I suggest you to modify it to return the index and the element as a pair of int values.
Your sorting routine will look something like this :
new_array := []
while(length(original_array) > 0)
min, min_index := find_min(original_array)
new_array.append(min)
original_array.delete(min_index)
You can use something like this to return an int pair :
class IntPair {
int min;
int index;
public IntPair(int x, int y) { this.min=x; this.index=y; }
public int get_min() { return min; }
public int get_min_index() { return index; }
}
Also, since you will de doing insertion and deletion, use ArrayList instead. It has methods to remove element at a particular index and append elements to it.
Note: Your approach outlined is close to Selection Sort algorithm in which we divide the array into two parts (sorted left part and unsorted right part) and repeatedly pick the smallest element from the right of the array and swap it with the left part's rightmost element.
min := array[0]
for(i := 0; i < array.length; ++i)
for(j := i+1; j < array.length; ++j)
if(array[j] < min)
min = array[j]
break
swap(array[i], array[j])
In this case, you dont need two arrays and you dont need to delete or insert elements into an array either.
I am trying to fill an array with random int values from 0 to 6. To control my code i am printing out the random values I generate. I try to exclude duplicates in the nested if-statement inside the for-loop, but when I run the code I get my seven values, but some of them are still duplicated. Can someone please help me?
Here is my code:
import java.util.Random;
public class TesterArrayer
{
public static void main(String[] args)
{
int size = 7;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int x =0; x < size; x++)
{
int randomValue = randomNumber.nextInt(6);
if (randomValue != randomArray[x])
{
randomArray[x] = randomValue;
}
}//End for-loop
for (int y = 0; y < size; y++)
{
System.out.println(randomArray[y]);
}
}
}
public static void main(String[] args) {
int size = 7;
boolean add = true;
int counter = 0;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int j = 0; j < size; j++)
{
randomArray[j] = -1;
}
while (counter < size) {
add = true;
int randomValue = randomNumber.nextInt(7);
for (int x = 0; x < size; x++) {
if (randomValue == randomArray[x]) {
add = false;
}
}// End for-loop
if(add)
{
randomArray[counter] = randomValue;
counter++;
}
}
for (int y = 0; y < size; y++) {
System.out.println(randomArray[y]);
}
}
Try something like this. You don't want to add the number unless it's not already in the list. Also for your random you need 7 instead of 6 if you want 0-6.
This code will fill your array with 0-6 not repeating any numbers.
If you only want the numbers 0..length-1 in random order you can do something like this:
int length = 7;
List<Integer> list = new ArrayList<>(length);
for(int i=0; i<length; i++){
list.add(Integer.valueOf(i));
}
//list is now in order, need to randomly shuffle it
Collections.shuffle(list);
//now list is shuffled, convert to array
int array[] = new int[length];
for(int i=0; i<length; i++){
array[i] = list.get(i);
}
Change minLimit, maxLimit and noOfItems to get random Numbers
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 6;
public static final int minLimit = 0;
public static final int noOfItems = 7;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit - minLimit + 1 ) + minLimit );
Integer[] randomUniqueIntegers = uniqueRandomIntegerSet.toArray( new Integer[0] );
}
}
As you should use a more optimal data structure for this approach, as mentioned in the other answer and comments, you can still accomplish this with an array of course. As you have defined the problem you would need to change int randomValue = randomNumber.nextInt(6); to int randomValue = randomNumber.nextInt(7); or else this will loop infinitely as there is no possible way to have no duplicates in a size 7 array with only 6 values.
You can do something like this to modify your code for it to work:
boolean flag = false;
for(int x = 0; x < size; x++)
{
int randomValue = randomNumber.nextInt(7);
for (int i = 0; i < x; i++)
{
if (randomValue == randomArray[i])
{
//randomArray[x] = randomValue;
flag = true;
x--;
}
}
if (!flag)
randomArray[x] = randomValue;
flag = false;
}//End for-loop
This code is simply flagging when it sees a duplicate value in the array already and will skip this value and decrement the x value so that it will create another random value for this spot in the array.
byte[] source = new byte[1024];
Random rand = new Random();
rand.nextBytes(source);
I'm completely new in Java. I am writing an Android game, and I need to generate an array of int arrays that contains all possible sums (excluding combinations that contains number 2 or is bigger than 8 numbers) that add up to a given number.
For example:
ganeratePatterns(5) must return array
[patternNumber][summandNumber] = value
[0][0] = 5
[1][0] = 1
[1][1] = 1
[1][2] = 1
[1][3] = 1
[1][4] = 1
[2][0] = 3
[2][1] = 1
[2][2] = 1
[3][0] = 4
[3][1] = 1
I already try to do this like there Getting all possible sums that add up to a given number
but it's very difficult to me to make it like this http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html
Solution
int n = 10;
int dimension = 0;
//First we need to count number of posible combinations to create a 2dimensionarray
for(List<Integer> sumt : new SumIterator(n)) {
if(!sumt.contains(2) && sumt.size() < 9) {
dimension++;
}
}
int[][] combinationPattern = new int[dimension][];
int foo = 0;
for(List<Integer> sum : new SumIterator(n)) {
if(!sum.contains(2) && sum.size() < 9) {
System.out.println(sum);
combinationPattern[foo] = toIntArray(sum);
foo++;
}
}
It's work not 100% correctly, and very pretty, but it is enough for my game
I have used SumIterator class from here SumIterator.class
I have to changed this code for(int j = n-1; j > n/2; j--) { to this for(int j = n-1; j >= n/2; j--) { because old version doesn't return all combinations (like [5,5] for 10)
And I used toIntArray function. I have founded hare on StackOverflow, but forget a link so here it's source:
public static int[] toIntArray(final Collection<Integer> data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection<Integer> effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList<Integer>(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
This is not the most beautiful code, but it does what you would like, having modified the code you referenced. It is also quite fast. It could be made faster by staying away from recursion (using a stack), and completely avoiding String-to-integer conversion. I may come back and edit those changes in. Running on my pretty outdated laptop, it printed the partitions of 50 (all 204226 of them) in under 5 seconds.
When partition(N) exits in this code, partitions will hold the partitions of N.
First, it builds an ArrayList of string representations of the sums in space-delimited format (example: " 1 1 1").
It then creates a two-dimensional array of ints which can hold all of the results.
It splits each String in the ArrayList into an array of Strings which each contain only a single number.
For each String, it creates an array of ints by parsing each number into an array.
This int array is then added to the two-dimensional array of ints.
Let me know if you have any questions!
import java.util.ArrayList;
public class Partition
{
static ArrayList<String> list = new ArrayList<String>();
static int[][] partitions;
public static void partition(int n)
{
partition(n, n, "");
partitions = new int[list.size()][0];
for (int i = 0; i < list.size(); i++)
{
String s = list.get(i);
String[] stringAsArray = s.trim().split(" ");
int[] intArray = new int[stringAsArray.length];
for (int j = 0; j < stringAsArray.length; j++)
{
intArray[j] = Integer.parseInt(stringAsArray[j]);
}
partitions[i] = intArray;
}
}
public static void partition(int n, int max, String prefix)
{
if(prefix.trim().split(" ").length > 8 || (prefix + " ").contains(" 2 "))
{
return;
}
if (n == 0)
{
list.add(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--)
{
partition(n - i, i, prefix + " " + i);
}
}
public static void main(String[] args)
{
int N = 50;
partition(N);
/**
* Demonstrates that the above code works as intended.
*/
for (int i = 0; i < partitions.length; i++)
{
int[] currentArray = partitions[i];
for (int j = 0; j < currentArray.length; j++)
{
System.out.print(currentArray[j] + " ");
}
System.out.println();
}
}
}