Using import java.util.Random; nextInt and user input - java

I am fairly new to java so this will probably seem like a basic question. I am trying to use the random java.util and nextInt to create a random number in a range specified by user input and then cast it as a character, to then be stored in an array;
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
However, because I want nextInt to use user Input, and although im controlling the range of values, im guessing the error is caused because nextInt thinks numberOfRegions could be 0?
// Map Class
import java.util.Random;
public class map
{
// number of grid regions
private int numberOfRegions;
private boolean correctRegions = false
// grid constants
private int xCord = 13; // 13 so the -1 makes 12 for a 12x12 grid
private int yCord = 13;
// initiate grid
private int[][] gridCells = new int[xCord][yCord];
Random r = new Random();
map() { }
// ask for number of regions
public void regions()
{
keyboard qwerty = new keyboard(); // keyboard class
while(correctRegions = false)
{
System.out.print("Please enter the number of regions: ");
numberOfRegions = qwerty.readInt();
if(numberOfRegions < 2) // nothing less then 2 accepted
{
correctRegions = false;
}
else if(numberOfRegions > 4) // nothing greater then 4 accepted
{
correctRegions = false;
}
else
{
correctRegions = true;
}
}
}
// fills the grid with regions
public void populateGrid()
{
for(int x =0; x<gridCells[x].length-1; x++) // -1 to avoid outofboundsexception error
{
for(int y =0; y<gridCells[y].length-1; y++)
{
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
}
}
}
public void showGrid()
{
for(int x=0;x<gridCells[x].length-1; x++)
{
for(int y=0; y<gridCells[x].length-1; y++)
{
System.out.print(gridCells[x][y] + " ");
}
System.out.println();
}
}
}

public void populateGrid()
{
for(int x =0; x<gridCells[x].length-1; x++) // -1 to avoid outofboundsexception error
{
for(int y =0; y<gridCells[y].length-1; y++)
{
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
}
}
}
This is bogus, either you do index < array.length or index <= array.length-1.
index < array.length-1 is most likely not what you intended.
Also, if you get compilation errors, it is maybe because you did not initialize numberOfRegions. Normally, thats not an error but a warning, but maybe your compiler is set to issue an error in this case. Try
private int numberOfRegions = 0;

you have to know how the java.util.random works.
Random r = new Random();
int number = r.nextInt(numberOfRegions);
this will produce an integer from zero (0) to ur numberRegions.
to exclude zero from ur possible range of random number generated, do something like this
int number = 1 + r.nextInt(numberOfRegions);
with this, the minimum number that can be generated is 1
int number = 2 + r.nextInt(numberOfRegions);
with this, the minimum number that can be generated is 2
...and so on

Well I have found something:
Your while condition is an assignment:
while(correctRegions = false)
You should write:
while(correctRegions == false) // == is a boolean operator, = is an assignment

Related

Creating an array between two integers w/ math.random as part of sequential search [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an assignment where the user is asked for a number between 50 and 400. If the number is found in the array printed beforehand, the program should print the index location. If not, the program prints -1. My problem is I can't figure out how to make it so the array starts at 50, not 0.
This is my code thus far (ignore the comments):
import java.util.Scanner;
public class Assignment_7
{
public static void main(String[] args)
{
int n,i,flag1 = 0; //setting all the variables
//flag is to indicate if a number was in the list
int[] arra; // creating array
arra = new int[100]; //initializing array
for(i = 0; i < 100; i++)//start of loop for array itself
{
int randomNum = (int)(Math.random() * 401);//array need the number between 0 and 400
//(one less than 401 is maximum for randomization)
arra[i] = randomNum; // setting array to random set of number between 0 and 400
}
for(i = 0; i < 100; i++)
{
System.out.print(arra[i]+" ");// array is printed
}
System.out.println("\nInsert a number between 50 and 400: ");
Scanner s = new Scanner(System.in); // setting scanner
n = s.nextInt(); // setting n (whatever number the user input) as int
flag1=0; // if flag gets set to 1 it needs to be reset to 0
for (i = 0; i < 100; i++)
{
if(arra[i] == n) //if the number is indeed on the list
{
flag1=1; // in case the number is on the list
System.out.println(i+1);
}
}
if(flag1 == 0)// if the flag was set to 1 before (the number was in the list), this condition fails and drops down to the next
{
System.out.println(-1); // n is not found, so it prints -1
}
}
}
I still remember the days back to school!
Just simply add the base value outside the random method, and subtract it from the upper bound:
int randomNum = 50 + ((int)(Math.random() * (400 - 50) + 1));
Of course, math expressions were expanded such that you can read the intend.
With current requirements
Need to use only array with linear scan
Prints the first seen occurrence(index) for a number (the number can appear multiple times)
start + new Random().nextInt(end - start) (includes start, excludes end)
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;
public class Assignment_7 {
public static void main(String[] args) {
final int startRange = 50; // inclusive
final int endRange = 400; // exclusive
final int count = endRange - startRange;
final Random random = new Random();
int[] numbers = IntStream.range(0, count).map(i -> random.nextInt(count) + startRange).toArray();
System.out.println(Arrays.toString(numbers));
System.out.println("Insert a number between " + startRange + "(inclusive) and " + endRange + "(exclusive)");
final Scanner scanner = new Scanner(System.in);
final int guess = scanner.nextInt();
boolean found = false;
for (int index = 0; index < count; index++) {
if(numbers[index] == guess) {
System.out.println(index);
found = true;
break;
}
}
if(!found) {
System.out.println(-1);
}
}
}
Optimization
If other other data structures are allowed, then we can use Map for lookup.
Also, if the guess is performed many times, Map will surely help
static void efficientForRepeatedGuessAndLongRanges(int startRange, int endRange) {
final int count = endRange - startRange;
final Random random = new Random();
int[] numbers = IntStream.range(0, count).map(i -> random.nextInt(count) + startRange).toArray();
System.out.println(Arrays.toString(numbers));
Map<Integer, Integer> valueToFirstSeenIndexMap = new HashMap<>();
IntStream.range(0, count).forEach(i -> valueToFirstSeenIndexMap.putIfAbsent(numbers[i], i));
int guess = -1;
do {
System.out.println("Guess a number between " + startRange + "(inclusive) and " + endRange + "(exclusive). Press -1 to stop");
final Scanner scanner = new Scanner(System.in);
guess = scanner.nextInt();
System.out.println(valueToFirstSeenIndexMap.getOrDefault(guess, -1));
} while (guess != -1);
}

Program starts misbehaving after a certain threshold

I have a homework task as follows:
The bin packing problem is to pack the objects of
various weights into containers. Assume each
container can hold a maximum of 10 pounds. The
program uses an algorithm that places an object into
the first bin in which it would fit. Your program should
prompt the user to enter the total number of objects
and the weight of each object. The program displays
the total number of containers needed to pack the
objects and the content of each container. Here is a
simple run of the program:
Enter the number of objects: 6
Enter the weight of the objects: 7 5 2 3 5 8
Container 1 contains objects with weight: 7 2
Container 2 contains objects with weight: 5 3
Container 3 contains objects with weight: 5
Container 4 contains objects with weight: 8
Now I have decided to try making it smarter and optimize the object allocation. It seemed to be working fine, but when I started testing using more numbers than the sample run I noticed that the highest I can go is 27 objects. Anything higher and I start getting a few containers at the end of the execution that could be merged into a single one. Any ideas and suggestions are welcome. Thank you in advance!
package classwork;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class BinPacking {
private static final int binLimit = 10;
public static boolean lessThanLimit(int a, int b) {
if (a + b < binLimit) {
return true;
} else {
return false;
}
}
public static boolean perfectFit(int a, int b) {
if (a + b == binLimit) {
return true;
} else {
return false;
}
}
public static boolean weightsLeft(boolean[] a) { // check if there is one more item that has not been binned yet.
for (boolean b : a) {
if (b) {
return true;
}
}
return false;
}
public static ArrayList<int[]> distributeObjects(int[] weights) {
int counter = 0;
boolean[] objectAssigned = new boolean[weights.length]; // array to track which objects have been assigned already
ArrayList<int[]> result = new ArrayList<int[]>(); // list of int[] to be returned
for (int i = 0; i < weights.length; i++) {
ArrayList<Integer> currentBin = new ArrayList<Integer>(); // list to store the values of the weights in currrent bin
int currentBinWeight = 6;
if (!objectAssigned[i]) {
currentBin.add(weights[i]);
currentBinWeight = weights[i];
objectAssigned[i] = true;
} else
counter = 1;
stupidLoopThatWontBreak:
while (currentBinWeight < binLimit && counter < 1) {
counter = 1;
if (!weightsLeft(objectAssigned)) { // break loop if no more weights left
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
break stupidLoopThatWontBreak;
}
for (int j = i + 1; j < weights.length; j++) {
if (perfectFit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight += weights[j];
objectAssigned[j] = true;
break stupidLoopThatWontBreak;
}
if (lessThanLimit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBinWeight += weights[j];
currentBin.add(weights[j]);
objectAssigned[j] = true;
}
}
}
// convert arraylist to int[] and add it to result. Java 8+ feature
if (!currentBin.isEmpty()) {
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
counter = 0;
}
}
return result;
}
public static void main(String[] args) {
System.err.println("Container weight limit is " + binLimit);
Scanner in = new Scanner(System.in);
//Test numbers 7, 5, 3, 2, 5, 8
// System.out.print("Enter the weights of the objects you want to put into the bins: ");
// String input = in.nextLine();
// in.close();
//========================Random numbers for testing======================
String input = "";
Random ran = new Random();
System.out.print("Enter number of weights to be randomly generated: ");
int num = in.nextInt();
in.close();
for (int i = 0; i < num; i++) {
input += (ran.nextInt(binLimit) + 1) + " "; //+1 to not have zeroes
}
//========================End of random numbers===========================
ArrayList<Integer> list = new ArrayList<Integer>();
String[] str = input.trim().split(" "); // trim surrounding spaces, use space char as separator
for (String a : str) {
list.add(Integer.valueOf(a));
}
// sort the list in a descending order
Collections.sort(list);
Collections.reverse(list); // this could be avoided if I started checking from the last index in distributeObjects()
System.out.println("The generated and sorted descendingly weights are:");
System.out.println("\n" + list.toString() + "\n");
int[] weights = new int[list.size()];
for (int a = 0; a < weights.length; a++) {
weights[a] = list.get(a);
}
ArrayList<int[]> bins = distributeObjects(weights);
for (int i = 0; i < bins.size(); i++) {
System.out.println("Container " + (i + 1) + " contains objects with weight: " + Arrays.toString(bins.get(i)));
}
}
}
Since I cannot comment, I am posing this as an answer -
Run above code with "10 9 8 8 8 7 7 7 6 6 6 5 5 5 4 4 4 4 4 3 3 2 2 2 2 2 2 2 1 1" as input array and you will see the problem being caused by 'counter' variable. If you replace 'counter=1;' from else with 'continue;' it should work for this input. You still need to test this for other inputs. Also, the above code needs refactoring - for example - use either list or weights. Both are nor required.
I tried not to distort your code too much, but this should give you your desired output. The problem was with your second loop, it caused some trouble with the counter variable since counter was never set back to 0 at the end of your loop if the bin should not already be added (when you did not find the first weight that has to be added to the bin).
The easiest way to fix your program is simply to move counter = 0; inside the if statement where you check if there is already a weight inside of the bin or not outside of the if block.
I removed the "stupidLoopThatWouldNotBreak" below and replaced it with another for loop, that looks through all remaining weights if there is one that can fit.
public static ArrayList<int[]> distributeObjects(int[] weights) {
boolean[] objectAssigned = new boolean[weights.length]; // array to track which objects have been assigned already
ArrayList<int[]> result = new ArrayList<int[]>(); // list of int[] to be returned
for (int i = 0; i < weights.length; i++) {
ArrayList<Integer> currentBin = new ArrayList<Integer>(); // list to store the values of the weights in currrent bin
int currentBinWeight = 0;
//This loop searches for the first unused Weight, so you do not need `count` anymore
for (int j = i; j < weights.length; j++) {
if (!objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight = weights[j];
objectAssigned[j] = true;
break;
}
i = j; //You can skip all iterations with used weights
}
for (int j = i; j < weights.length && currentBinWeight < binLimit; j++) {
if (perfectFit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight += weights[j];
objectAssigned[j] = true;
break; //this break gives some performance bonus
}
if (lessThanLimit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBinWeight += weights[j];
currentBin.add(weights[j]);
objectAssigned[j] = true;
}
}
// convert arraylist to int[] and add it to result. Java 8+ feature
if (!currentBin.isEmpty()) {
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
}
}
return result;
}
You can further enhance your code if you split this loop up. You can add more functions like the two helperfunctions perfectFit and lessThanlimit. You can for example add another function that will search for the first empty element, maybe even add it to the bin. Also the 2 functions you already have could be merged into one function called addWeight or attemptAdd. Furthermore you could create seperate classes for the bin and for the weights.

trying to add the sum of random ints in a temporary array and have the highest sum be output

my program is a kind of game. It gives the user 3 boards(arrays) of random ints and has them choose which board they think has the highest sum of numbers all within a time limit. I cant figure out how to add the sums of the individual arrays by using a temp array. I'm honestly just really stuck and don't know where to go from here. Any help would be appreciated. Ive been at this for hours.
import java.lang.reflect.Array;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class game
{
static Scanner scan = new Scanner(System.in); // Holds a local scanner
private static int secondsLeft; // Number of seconds after each turn
private static int score = 0; // Score variable which you update
private static NonBlockingHasNext t = new NonBlockingHasNext(); // Special class for timer
private static int [][][] gameBoard = new int [3][3][3]; // TODO 2: Initialize to a new 3x3x3 array
//static int row = 0;
//static int column = 0;
//static int depth = 0;
public static void main(String[] args)
{
// Give user instructions and begin
System.out.println("You will be presented 3 3x3 boards of random numbers, labeled 1, 2 and 3.");
System.out.println("Quickly select the board you believe to contain the largest sum of 9 numbers" +
" by entering the board number and pressing enter");
System.out.println("Press any key and hit enter to begin...");
scan.nextLine();
int numTurns = 10;
for (int i = 0; i < numTurns; i++)
{
reInit3dBoard();
print3dBoard(i, numTurns);
int choiceMade = countDownTimer();
choiceMade--; // Decrement to match with 0-indexed arrays
analyzeChoice(choiceMade);
}
}
//////////////////////////////////////////////////////
// countDownTimer() counts down from 10 seconds. Returns
// the user input if the value that is input is a 1, 2
// or 3. If the value is something else or no value is
// input, this method returns a -1.
//////////////////////////////////////////////////////
private static int countDownTimer()
{
// Some really complicated stuff to work around Java shortcomings.
// Basically, this code creates a new "thread" which allows us to
// run other code while a scanner in NonBlockingHasNext is waiting
// for a user input.
t = new NonBlockingHasNext();
(new Thread(t)).start();
System.out.println("Seconds left to make choice: ");
for (int i = 10; i > 0; i--)
{
secondsLeft = i;
System.out.print(secondsLeft + "...");
// Sleep for 1 second and....
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace(); }
// ...check again for input. If received a valid input in time, then return it
if (t.hasNext())
{
// Make sure choice is valid (1, 2 or 3)
int choice = t.nextInt(); //scan.nextInt();
if (choice >= 1 && choice <= 3)
{
System.out.println("\nYou chose grid #" + choice + " with " + secondsLeft + " seconds left!");
return choice;
}
}
}
// If we get here, then no choice was made!
System.out.println("\nNo choice made!");
return -1; // If no valid choice made
}
//////////////////////////////////////////////////////
// Simply assigns each element of the 3x3x3 3D board
// a random number from 1-9 (should not see 0's or 10's)
//////////////////////////////////////////////////////
private static void reInit3dBoard(){
Random rand = new Random();
{
for(int row=0;row<gameBoard.length; ++row){
for(int column=0;column<gameBoard[row].length; ++column){
for(int depth=0;depth<gameBoard[row][column].length; ++depth )
gameBoard[row][column][depth]=rand.nextInt(9)+1;
}
}
}
}
// TODO 3: Generate a random assignment of the gameBoard variable
// (see member variables) as described in the method header above.
// NOTE: You can just overwrite the values there.
private static int[][] randomFill() {
// TODO Auto-generated method stub
return null;
}
//////////////////////////////////////////////////////
// Prints the 3x3x3 3D board out to the console. It
// should print 3 2d boards. The line directly above each board
// should be labeled "Board 1:", "Board 2:" or "Board 3:".
// The line directly below each board should be blank.
//////////////////////////////////////////////////////
private static void print3dBoard(int turn, int numTurns)
{
System.out.println("--------------------------Turn " + (turn+1) + "/" + numTurns + "--------------------------");
for(int row=0; row<gameBoard.length; ++row)
{
System.out.println("\n\nboard:"+ row);
//System.out.println(Arrays.deepToString(gameBoard));
for(int column=0; column<gameBoard.length; ++column)
{System.out.println();
for(int depth=0; depth<gameBoard.length; ++depth)
{System.out.print(gameBoard[row][column][depth]);
}
}
}
}
// TODO 4: Print out the 3d board as described in the method header above.
// Make sure to label the boards 1-3 and not 0-2.
//////////////////////////////////////////////////////
// This method analyzes the choice made by the user
// conveniently passed into us for array-indexing purposes
// as a 0, 1 or 2.
//////////////////////////////////////////////////////
private static void analyzeChoice(int choiceMade)
{
// TODO 5: Create a counter array and use several FOR loops
// to compute the sum of each of the 3 boards.
int temp [][][] = new int [3][3][3];
temp = gameBoard;
int sum = 0;
// TODO 6: From your counter array, compute the max score
// TODO 7: Print out the score of all three boards (e.g., "Board 1 value: 34"). Number
// the boards 1-3 b/c this is what the user saw when selecting.
// Next to the selected board, add the string "(Right)" or "(Wrong)" if their guess
// was correct (i.e., the max board). Also, update the score by adding the number
// of seconds left when the guess was made.
// HINT: At this point, the member variable "score" holds the current score and the
// member variable "secondsLeft" holds the seconds left when the last selection was made.
// Print out the current score
System.out.println("\n***Current Score: " + score);
}
}
Just think of each board as 27 different variables. For example:
int space1 =gameBoard[1][1][1]
int space2 =gameBoard[1][1][2]
.
.
.
.
.
int space27 =gameBoard[3][3][3]
Then just add up spaces 1-27
This would be much easier than using a temporary array
If you want, you can store the sum of each board in its own array afterwords:
score1=space1+space2+space3...
int scores[3];
scores[1]=score1;
etc.
Edit: If you HAVE to use a temporary array just do it like this:
int score[3];
score[1]=gameBoard[1][1][1]+gameBoard[1][1][2]+gameBoard[1][1][3] ...
And skip the middleman
Maybe you should add another function which will count sum of array of type 3x3:
public static int countSum(int[][] arr) {
if(arr == null) return 0;
int sum = 0;
for(int i = 0; i < arr.length;i++) {
int[] arr1 = arr[i];
for(int j = 0; j < arr1.length; j++) {
sum+=arr1[j];
}
}
return sum;
}
and rewrite your analyzeChoice method:
private static void analyzeChoice(int choiceMade)
{
int temp [][][] = new int [3][3][3];
temp = gameBoard;
int[] sums = new int[]{0, 0, 0}; /*sums for each table*/
for(int i = 0; i < temp.length; i++) {
int[][] inner_arr = temp[i];
sums[i] = countSum(inner_arr);
}
int maxsum = 0;
int maxint = 0;
for(int i = 0; i < sums.length; i++) {
if(sums[i] > maxsum) {
maxsum = sums[i]; maxint = i;
}
}
if(maxint == choiceMade) {
score++;
}
// Print out the current score
System.out.println("\n***Current Score: " + score);
}

Math.random value keeps being chosen?

Ok so basically, for some reason, the first array value of "a0" keeps on being chosen in the for loop math.random section. Why is it doing this and how can I fix it? (P.S., you don't have to read every single String array value)
public class Battleship extends JPanel
{
public static void main(String[] args)
{
String[][] pos = new String[10][10];
...
//we initialize pos here
...
int horcol = 0;
boolean[][] tof = new boolean[10][10];
boolean taken = false;
int vertcol = 0;
for(int k=0; k<=9;k++)
{
for(int l=0;l<=9;l++)
{
if(taken == false)
{
int random = (int)Math.random()*15;
if(random == 1 || random == 2)
tof[k][l] = true;
taken = true;
vertcol = k;
horcol = l;
}
else
{
tof[k][l] = false;
}
}
}
}
The problem here is remarkably simple.
The issue is with your parenthasis!
Currently you have this:
int x = (int)Math.random()*15;
So the computer will first do Math.random(), which will return a float between 0 and 1 (something ike 0.648294), then make that into an int, which will always be 0 because that truncates the number, then multiply by 15, which is still 0.
You need to add parenthesis around the Math.random()*15 part, like this:
int x = (int)(Math.random()*15);
That will first multiply the random value by 15, and THEN convert it to an int (and truncate in the process).

Need to work on an array recursively, trouble passing data, java

Ok, I am having a really beginner mistake here, but I can't think of what I need to do. I have an array permArray that I am recursively filling with possible permutations. I have a public method that gets the parameters ready, then I work on the array in the private method that calls itself to work on smaller and smaller parts.
The problem I am having, is how do I pass the finished array back to the public method. Would I return the array every time I am finished with the recursion (after I have placed the last element in each section, where the section size is 1).
Oh, and also, this is practice, not homework.
//todo:
//need to determine what is wrong with my array of linked lists
package wordchains;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.xml.soap.Node;
/**
*
* #author Samuel French
*/
public class WordChains {
public static void main(String[] args) {
//variables
int numWords = -1; //This will hold the number of words the user is inputting
String userInput; //holds the user input to be broken up into a string array
//Get the user's input, 0 is the quit value
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of words: ");
numWords = sc.nextInt();
System.out.println(">");
sc.nextLine();
userInput = sc.nextLine();
String[] inputWords = userInput.split("\\s+");
int numElements = inputWords.length;
int numOfPerms = numOfPerms(numElements);
//We will start by checking the last letter of the first word
char cTest;
int wordChecking = 0;
int[][] permArray = genPerms(numElements, numOfPerms);
for (int col = 0; col < numOfPerms; col++) {
System.out.println();
for (int row = 0; row < numElements; row++) {
System.out.print(permArray[col][row] + " ");
}
}
}
public static int numOfPerms(int numElements) {
int numOfPerms = numElements;
numElements--;
while (numElements > 0) {
numOfPerms = numOfPerms * numElements;
System.out.println(numOfPerms);
numElements--;
}
return numOfPerms;
}
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
//either do it like this or create an array of head nodes
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
LinkedList tempList = new LinkedList();
for (int x = 0; x < numElements; x++) {
tempList.addLast(x);
}
for (int x = 0; x < totPerms; x++) {
elementsLeftList.add((LinkedList<Integer>) tempList.clone());
}
return privateGenPerms(permArray,elementsLeftList,totPerms,0,0,totPerms);
}
private static void privateGenPerms(int[][] permArray, List<LinkedList<Integer>> elementsLeftList, int totalPermutations, int elementPlacing, int sectionBegin, int sectionSize) {
//variables-
//totalPermutations - the total number of permutations in the whole problem
//elementPlacing - the element currently being placed's position, corresponds to the rows of permArray
//elementPlacingIndex - the number of times the element currently being placed has been placed
//sectionSize - the size of the total working section. First time this is the # of permutations
//permCounter - this counter counts the permutation working with within the section
//sectionBegin - counts the beginning of the section working with
//2 Data structures:
//permArray - 2d the array of permutations
//elementsLeftList - list of lists of elements left, corresponds to each permutation
int totalNumberOfElements = permArray[0].length;
//
int numberOfElementsLeftToPlace = totalNumberOfElements - elementPlacing;
//
int permCounter = sectionBegin;
//Base case
if (numberOfElementsLeftToPlace == 1) {
for (int x = 0; x < totalPermutations; x++) {
permArray[x][totalNumberOfElements - 1] = (int) elementsLeftList.get(permCounter).remove(0); //may need to be a remove 1, not sure
}
return; //need to decide what I am going to do here
}
//
int elementPlacingIndex = 0;
int elementCurrentlyPlacing = 0; //could be a 1, don't remember
//
int numberOfTimesToPlaceWithinCol = (sectionSize / numberOfElementsLeftToPlace);
//
//
for (; permCounter < (sectionBegin + sectionSize); permCounter++) {
//when we need to switch to a different partition of the section
if (elementPlacingIndex == numberOfTimesToPlaceWithinCol) {
elementPlacingIndex = 0;
elementCurrentlyPlacing++;
}
permArray[permCounter][elementPlacing] = (int) elementsLeftList.get(permCounter).remove(elementCurrentlyPlacing);
elementPlacingIndex++;
}
for (int newSectionBegin = sectionBegin; newSectionBegin < (sectionBegin + sectionSize); newSectionBegin = newSectionBegin + numberOfTimesToPlaceWithinCol) {
privateGenPerms(permArray, elementsLeftList, totalPermutations, (elementPlacing + 1), newSectionBegin, (sectionSize / numberOfElementsLeftToPlace));
}
}
}
The array is passed-by-reference, so any changes you make in the private function will be permanent and you do not need to return the modified array again.
I have not looked at your logic to see if this is the correct way to do it in your case though.

Categories