Generate a random number that is not in array [closed] - java

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 7 years ago.
Improve this question
so I have this code that basically reads from a text file. The text file contains 9 rows of 9 random numbers, as well as 9 columns - it is for a 9 x 9 Sudoku puzzle, so think of it that way.
Here is what the text file that is being read in looks like:
1,1,0,0,1,0,0,0,0
1,0,0,1,1,1,0,0,0
0,1,1,0,0,0,0,1,0
1,0,0,0,1,0,0,0,1
1,0,0,1,0,1,0,0,1
1,0,0,0,1,0,0,0,1
0,1,0,0,0,0,1,1,0
0,0,0,1,1,1,0,0,1
0,0,0,0,1,0,0,1,1
For this particular facet, the values from the file are used to determine if a cell is empty is or not. If it is a number 1, than that cell will contain some sort of value, but if the number is 0, that cell is empty, and will need to have a random number generated for it.
How do I make it so that when Math.random is used to generate said random number, it checks to see if that same number is already in that row, and if it is, generate a new one?
Here is the code. Thanks in advance...
import java.util.*;
import java.io.*;
import java.math.*;
public class RandomNumberGenerator {
// set Sudoku value rows to unchangeable number 9
private static final int ROWS = 9;
// set columns to unchangeable number 9
private static final int COLUMNS = 9;
public static void main(String[] args) { // main
// load in text file
ReadSudokuFile puzzle = new ReadSudokuFile("puzzle.txt");
// set array to get number values from getDisplayValues method
int puzzleNumbers[][] = puzzle.getDisplayValues();
// rows loop
for (int rows = 0; rows < ROWS; rows++) {
// columns loop
for (int columns = 0; columns < COLUMNS; columns++) {
// A cell containing the number 0 is an empty input box in Sudoku grid
if (puzzleNumbers[rows][columns] == 0) {
// populate that empty input box to a random number between 1 and 9
puzzleNumbers[rows][columns] = (int)((Math.random() * 9) + 1); // cast Math.random as an int & add 1 so a zero doesn't display
}
} // end columns loop
// print out the array to console
System.out.println(Arrays.toString(puzzleNumbers[rows]));
} // end rows loop
} // end main
}
There is another file that this file pulls info from, but it is not relevant here for this specific question. Thanks again!

One possible method, using Java 8, is to filter members of the row from a stream of random numbers. Something like:
Random rand = new Random();
puzzleNumbers[row][col] = rand.ints(0, 10)
.filter(n -> Arrays.binarySearch(puzzleNumbers[row], 0, col, n) < 0)
.findAny().get();
I've left out the row and col iteration for clarity.
This can be extended fairly easily to filter out numbers in the row or 3x3 cell. Let me know in comments if you want examples for those.

well you can make a private method that checks that.
public boolean checkRow(int row,int generatedNum){
boolean flag = true;
for (int columns = 0; columns < COLUMNS; columns++) {
// A cell containing the number 0 is an empty input box in Sudoku grid
if (puzzleNumbers[row][columns] == generatedNum) {
flag = false;
break;
}
}
}

You can populate an ArrayList with the numbers from 1 to 9 and the get a random index. When you need start over, you can just reset the ArrayList.
public class Test {
public static void main(String[] args) {
final ArrayList<Integer> numbers = new ArrayList<>();
// Populate the ArrayList with numbers ( from 1 to 9 )
resetNumbers(numbers);
// Getting 5 random numbers from 1 to 9
for (int i = 0; i < 5; i++) {
System.out.println(getRandomIndex(numbers));
}
// Reset the number list
resetNumbers(numbers);
System.out.println();
// Get another 9 random numbers from 1 to 9
for (int i = 0; i < 9; i++) {
System.out.println(getRandomIndex(numbers));
}
}
public static void resetNumbers(ArrayList<Integer> list) {
list.clear();
populateList(list, 1, 9);
}
public static void populateList(ArrayList<Integer> list, int from, int to) {
for (int i = from; i <= to; i++) {
list.add(i);
}
}
public static int getRandomIndex(ArrayList<Integer> numbers) {
int index = (int)((Math.random() * numbers.size()) + 0);
int result = numbers.get(index);
numbers.remove(index);
return result;
}
}

Related

Fill array with zero in random places

So, what I am trying to do is to fill a 2D array with zeros in random places a specific amount of times. Let's say that it has to be 20 zeros in an array of 90 places. What I have done so far is to declare a 2D array and fill it with random numbers. And my next thought was to simply choose random positions and replace them with zeros. Any idea how I could do that?
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
myboard[i][j] = (int) (Math.random() * 10);
}
}
It is a rather simple way to achieve the goal, but it should do the job. So you need to get the length of each row. After you have done that you can call a function that will give you a random number between some start point and the length of the row. Here is some code sample to show you what I mean:
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
public class Example {
public static void main(String []args) {
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
// fill the row with random vals
myboard[i][j] = GetRandomNumber(0, myboard[i].length);
}
// sneak as much zeros as your heart content
int random = GetRandomNumber(0, myboard[i].length);
myboard[i][random] = 0;
}
System.out.println(Arrays.deepToString(myboard));
}
private static int GetRandomNumber(int min, int max) {
/*
min is the start point
max is the curr row len
*/
return ThreadLocalRandom.current().nextInt(min, max);
}
}
A pseudo code would look like:
while (num_zeros_filled < 20):
row = random()%total_rows
col = random()%total_cols
if (arr[row][col] == 0): # already filled in with 0
continue
else:
arr[row][col] = 0
num_zeros_filled += 1
This, however, could take infinite time theoretically if only those cells are generated which have already been filled with 0. A better approach would be to map the two-dimensional array into a 1-d array, and then sample out only from those cells which haven't been filled with 0 yet.

How to realign numbers from an Integer array to a Jtable?

Sorry for bad expression to make people confused, i edit my question again.
There is Integer array , it contains 29 numbers, These 29 numbres are made up of 0 to 10.
For example: Integer [ ] num ={ 0,3,4,5,6,1,3,10,4,3,1,0,2,2,3,4,1,0,8,7,6,6,5,8,9,0,5,10,8} I want to realign these numbers into Jtable(limits 6 rows,10 columns).
if 0 <= number < 5,i will call them "Small" number;
if 5 <= number < 10,i will call them “Big" number;
if number = 10, i will call them "P"number.
In a word, the 29 numbers are made up of 3 type number("Samll","Big","P").
In the array num, we can see first three number is belong to "Small" number,so they show one by one in c1,the fourth is 5,it is "Big"number,so it jump to next column, it goes c2,the remaining cells of c1 will not be used again. if the same type number is over 6,it wil turn right to next nearest cell to contiune showing(See 2nd sample image).others array numbers are the same logic,loop the array num and then show the numbers according to the number type in jtable.
The final result what i want in Jtable ,you can see below sample images i post. Anybody posts sample code will be very helpful to me,Thanks in advance!
Below sencond sample image, the red underline number total 10 "Small" numbers over 6, so turn to the right nearest cell to contiune showing. The green underline total 7 "Big" numbers ,because the sixth cell in c6 has been occupied, so it turns right to contiune showing after fifth cell
I wrote code just to create the 6 x 10 int matrix.
Here's the output from one of my many tests.
0 5 1 10 4 8 0 5 10 8
3 6 3 3 7
4 1 6
0 6
2 5 8 9
2 3 4 1 0
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing, that will help you learn how to create a Swing GUI. Skip the Netbeans section.
You will want to use a JTable to display your matrix.
When tackling a problem like creating your matrix, it helps to break it down into steps. Keep breaking it down into steps until you can code each step.
This task was so complicated, I had to print debug output to make sure I was making progress. Don't be afraid to put many System.out.print and System.out.println statements in your code. You can use a DEBUG boolean like I did to turn the extra print statements off.
Here's the complete runnable code to create the 6 x 10 matrix. I didn't check for more than 10 subsets of values. I left that for you.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RealignNumbers {
private static final boolean DEBUG = false;
public static void main(String[] args) {
RealignNumbers rn = new RealignNumbers();
int[] numbers = { 0, 3, 4, 5, 6, 1, 3, 10, 4, 3, 1, 0, 2, 2, 3, 4, 1, 0,
8, 7, 6, 6, 5, 8, 9, 0, 5, 10, 8 };
int[][] matrix = rn.realignNumbers(numbers);
printMatrix(matrix);
}
private static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
if (matrix[row][column] >= 0) {
String display = String.format("%3d", matrix[row][column]);
System.out.print(display);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public int[][] realignNumbers(int[] numbers) {
List<List<Integer>> matrixList = splitInput(numbers);
printList(matrixList);
int[][] matrix = fillMatrix(matrixList);
return matrix;
}
private List<List<Integer>> splitInput(int[] numbers) {
List<List<Integer>> matrixList = new ArrayList<>();
int number = numbers[0];
boolean isSmall = number < 5;
List<Integer> numberList = new ArrayList<>();
numberList.add(Integer.valueOf(number));
for (int index = 1; index < numbers.length; index++) {
if (numbers[index] == 10) {
// Finish prior List if exists
if (numberList.size() > 0) {
matrixList.add(numberList);
numberList = new ArrayList<>();
}
// Create numberList for 10
numberList.add(Integer.valueOf(numbers[index]));
matrixList.add(numberList);
// Start new List
numberList = new ArrayList<>();
} else {
boolean small = numbers[index] < 5;
if (isSmall == small) {
// Add number to List
numberList.add(Integer.valueOf(numbers[index]));
} else {
// Number is different; end list and start new List
matrixList.add(numberList);
numberList = new ArrayList<>();
numberList.add(Integer.valueOf(numbers[index]));
isSmall = small;
}
}
}
if (numberList.size() > 0) {
matrixList.add(numberList);
}
return matrixList;
}
private void printList(List<List<Integer>> matrixList) {
if (DEBUG) {
int count = 1;
for (List<Integer> numberList : matrixList) {
String display = String.format("%2d", count++);
System.out.print("List " + display + " ");
for (int number : numberList) {
display = String.format("%3d", number);
System.out.print(display);
}
System.out.println();
}
}
}
private int[][] fillMatrix(List<List<Integer>> matrixList) {
int masterColumn = -1;
int length = 6;
boolean firstTimeSwitch = true;
int[][] matrix = new int[length][10];
for (int[] row : matrix) {
Arrays.fill(row, -1);
}
for (List<Integer> numberList : matrixList) {
masterColumn++;
int column = masterColumn;
int row = 0;
for (int number : numberList) {
if (DEBUG) {
System.out.println("row " + row + " column " + column);
}
matrix[row][column] = number;
// Check if we hit the last row
// If so, increment columns
if (row < (length - 1)) {
row++;
} else {
if (firstTimeSwitch) {
length--;
firstTimeSwitch = false;
}
column++;
}
}
if (length < 6) {
firstTimeSwitch = true;
}
}
return matrix;
}
}
If you really want to do this, then think of a jTable much like a 2D array, for example, int[][] yourArray = new int[6][10];.
So the first number in your list goes at yourArray[0][0] = 0, and the next two go on the same column yourArray[1][0] = 3 and yourArray[2][0] = 4, and the next number 5 goes into a new column yourArray[0][1] = 5 and so on.
So when it comes to turning you could do something like this inside the loop that places numbers into the jTable:
if(row > rowCount) {
col++;
yourTableModel.setValueAt(number, row, col);
}
But to make sure that nothing overlaps when turning also use:
//Insert value if able
if(yourTableModel.getValueAt(row, col) != null){
row++;
yourTableModel.setValueAt(number, row, col);
}
//Move to next col if not able to fit the number within the row
else{
col++;
yourTableModel.setValueAt(number, row, col);
}

Generation of 4 non repeating random numbers using arrays in java

I have this array
int [] marc = new int[4];
i need to insert a set of non repeating random numbers in the range of 1-10 to it
i'm using this for loop to set random numbers
for (he = 0; he < 4; he++) {
marc[he] = rn.nextInt(10 - 1 + 1) + 1;
marc[he]++;
}
it gives me random numbers but repeated ones inside the array
i'm also using
java.util.Random;
Well, yes, numbers can be repeated while being random. You need to do your own logic to validate if they're already on the array, this can be done with the following code:
In the code I used an array of 10 elements to observe there aren't repeated numbers even on that situation.
import java.util.Random;
public class RandomNumbersNoRepeating {
public static void main(String[] args) {
int array[] = new int[10];
Random random = new Random();
//Fills the array
for (int i = 0; i < array.length; i++) {
boolean found = false;
int r = 0;
do {
found = false;
r = random.nextInt(10) + 1;
//Here we check if the number is not on the array yet
for (int j = 0; j < array.length; j++) {
if (array[j] == r) {
found = true;
break;
}
}
} while (found);
array[i] = r;
}
//Prints the array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Another possible solution, as given in a comment could be to shuffle an array from 1-10, and get the first four numbers
Using java.util.Random; will generate repetitive numbers more often when your range is small, which in your case is only 10. There is no condition in your code that checks whether the generated random number already exists in your array or not.
Before inserting a generated number in to the array, you first need to check whether that number already exists in your array. If it does not, you insert that number in the array, otherwise you generate a next random number.

Printing an array in a table format

I have an array filled with 50 numbers and cannot figure how to output the array into a table like format.
Currently when I print my array it is being outputted into one long line of numbers, and what I am aiming for is 10 lines, each consisting of 5 numbers.
Furthermore I would prefer each value to be a 3 digit value. So 1 would be represented as 001, to improve readability and presentation.
import java.util.*;
public class Random50 {
public static void main (String[] args)
{
final int MAX_SIZE = 50;
int[] r50 = new int[MAX_SIZE];
Random rand = new Random();
for (int i=0; i<r50.length; i++)
{
r50[i] = rand.nextInt(1000);
for (int j=0;j<i;j++)
{
if (j!=i && r50[i] == r50[j])
{
System.out.println("Duplicate: " + r50[i]);
r50[i] = rand.nextInt(1000);
}
}
}
System.out.printf(Arrays.toString(r50));
}
}
You really should only ask 1 question per post so I'll answer your first question - it makes it so other users can find relevant information in the future (not trying to be mean).
If you want to start printing on a new line every fifth number you could make use of the modulus operator %.
for(int i = 0; i < 50; i++){
if(i % 5 == 0){ // True every fifth value
System.out.print("\n"); // Print a new line
}
... // Your other code goes here
}

Adding to randomly generated scores to see if they add to 10 which are stored in an array

I need some help writing a program for an intro java class I'm taking. There is a homework assignment that requires us to generate a score that is no higher than 9 and pair them with another "person" whose score adds up to 10 with another person. There are 20 contestants in this "game". So far I created hypothetical rows and columns for the pairing of the 2 scores and nested 2 for loops and ended it off with an if to see if the rows and columns will add to 10.
The program did compile, but when running, it doesn't seem to give me a solution.
public static void main(String[] args) {
int rows = 2;
int cols = 10;
int[][] scoreTotal = new int[rows][cols];
for (int row = 0; row < rows; row++) {
int teamBlue = (int)(Math.random()* 10);
for (int col = 0; col < cols; col++) {
int teamRed = (int)( Math.random()* 10);
if (scoreTotal[row][col] == 10) {
System.out.println(scoreTotal);
}
}
}
}
Sorry if this is a very confusing or newbie question to be asking, but like I said i'm in an intro to java class.
Often when getting assignments we try to complete it all in one go, but you can try to abstract the problem away to smaller "components". Try to think of it as a recipe when cooking, you simply write the steps you need to take and then write out the code afterwards.
First, start off with your main method, you did that already
public static void main(String[] args) {
}
Next, you have one requirement that states
generate a score that is no higher than 9
So what you can do is create an array of "scores", and fill that with scores for each player (I used player instead of person since you mention "score" and "contestants").
public static void main(String[] args) {
// generate a score for each of the contestants
}
and pair them with another "person" whose score adds up to 10 with another person.
public static void main(String[] args) {
// generate a score for each of the contestants
// if score of player1 and another player is equal to 10, save pair
}
The if statement is kind of cumbersome, so we can try to break it down. To simplify things, try to think of only testing with one player to begin with.
public static void main(String[] args) {
// generate a score for each of the contestants
// take score of first player, s
// compare s + x = 10, where x is score of other player
// if x = 10 - s, save pair
}
Now we got something a bit more simple. Lets try putting in some code.
public static void main(String[] args) {
int[] scores = new int[20];
// generate a score for each of the contestants
for (int i = 0; i < scores.length; ++i) {
scores[i] = getRandomNumber();
}
// take score of first player, s
int s = scores[0]; // the first player is at index 0
// compare s + x = 10, where x is score of other player
for (int i = 1; i < 20; ++i) {
// note: We don't have to test against index 0 (that's the first player)
// so we start at index 1
// if x = 10 - s
int x = scores[i];
if (x == 10 - s) {
// save pair
}
}
}
public static int getRandomNumber() {
// todo: generate a random score between 0 and 9 and return it
return 4;
}
You seemed to know how to use the for loop in your original code. What you didn't do was assigning a value in the array. The scores[i] = x; (where x is an int) takes care of that, similar to assigning an int for instance, int a = 0. I used a method for generating a score that returns an int, since the implementation of how to get a random value is "not interesting" (so we abstract it away). So the for loop sets a score value for each index of the array.
Next, since the scores array have all the scores for the contestants, we need to pair them. Using some simple math, we construct an if statement that checks if the first player and a second player has scores that sum up to 10.
Next we need to save the pairs of contestants. You were on the right path of creating a two-dimensional array, one for holding the players, and the other dimension for the "teams". When filling this array, the 2D array can look something like this
| players |
| 0 1 |
-------+----+----+
team 0 | 0 | 1 |
team 1 | 3 | 7 |
team 2 | 8 | 9 |
-------+----+----+
i.e. we team up player 0 with 1, player 3 with player 7, and player 8 with player 9. We notice from this that the team index (0-2) is not related to the actual players, so we can conclude that we need a separate index for the teams.
public static void main(String[] args) {
// generate a score for each of the contestants
// create the team array, 10 teams each with 2 participants
// for every player: take score of player, s
// compare s + x = 10, where x is score of every other contestant
// if x = 10 - s
// assign the current team to player s and player x
// increment team integer (assign next team)
}
So using similar code to yours, we construct the teams array and assign the first team with our player, before we continue with the rest of the teams.
// create the team array, 10 teams, each with 2 participants
int[][] teams = new int[10][2];
// assign the first team to player 3 and player 7
teams[0][0] = 3;
teams[0][1] = 7;
This is just an example, where Team 0 is assigned two team members, one at index 0 and one at index 1, to player 3, and player 7.
This is great. We can now pair up one player with anyone of the other players. From this, we know that we need a counter for the "current team", since each contestant doesn't have to have a teammate in this round, and when one team is assigned, we should assign the next one.
public static void main(String[] args) {
int[] scores = new int[20];
// generate a score for each of the contestants
// ... same as before
// create the team array, 10 teams each with 2 participants
int[][] pairs = new int[10][2];
// create a team integer
int currentTeam = 0;
// for every player: take score of player, s
for (int i = 0; i < 20; ++i) {
// todo: test if player i is already in teams array and continue; if it is
int s = scores[i];
for (int j = i + 1; j < 20; ++j) {
// compare s + x = 10, where x is score of every other contestant
int x = scores[j];
// if x = 10 - s
if (x == 10 - s) {
// assign the current team to player i and player j
pair[currentTeam][0] = i;
pair[currentTeam][1] = j;
// increment team integer (assign next team)
++currentTeam;
}
}
}
}
Note that the second for loop starts from i + 1, since we already tested the players with lower indexes.
Also; You don't mention it, but there's a "hidden" constraint in this problem that each pair is exclusive, so one contestant can only participate one time. You should add a third for loop that checks if the teams array contains the player already.
So, by breaking down the problem we managed to get some code that may or not work, but the logic is there anyways created by reasoning, and that's always important when solving problems!
As it stands now, one can not easily help you except for writing out the program for you, as you did not submit any code, so instead of plainly doing the homework for you, here are some pointers: First, break down the problem. Read the problem carefully and then identify what you have to do. In doing so, you should arrive at several steps that can be turned into code.
Create twenty integers containing random numbers from 0-9 (or 1 to 9, the question doesn't really specify) and put them in an array.
For each score, find another score so the sum of them is 10 and store them as a pair. Again, it isn't really specified how you should store these pairs.
After finding all pairs, output them and any left-over scores that didn't get any matches.
So your in the loops:
for (int row = 0; row < rows; row++) {
int teamBlue = (int)(Math.random()* 10);// teamBlue never used
for (int col = 0; col < cols; col++) {
int teamRed = (int)( Math.random()* 10);// teamBlue never used
if (scoreTotal[row][col] == 10) {
// scoreTotal[row][col] never modified
// never reached because scoreTotal[row][col] == 0 by default
System.out.println(scoreTotal);
}
}
}
In other words your 2D array is full of 0's:
{ {0 0 0 0 0 0 0 0 0 0}
{0 0 0 0 0 0 0 0 0 0} }
Since you didn't do anything with the scores. You could:
public static void main(String[] args) {
int rows = 2;
int cols = 10;
int[][] scoreTotal = new int[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int randScore = (int)(Math.random()* 9) + 1;// in case you want a 1-9
scoreTotal[row][col] = randScore
}
}
}
This way you have a 2D array of scores:
{ {1 2 3 4 5 6 7 8 9 2} // row == 0, 1st player random scores
{1 2 3 4 3 5 6 7 8 9} } // row == 1, 2nd player random scores
//col index: 0 1 2 3 4 5 6 7 8 9
//eg. scoreTotal[2][4] would be 3
Now you can do anything you want with the scores. The pairing would depend on whether you want pair that only add up to 10 or some other rules.

Categories

Resources