How to randomly insert String numbers into an array-Java - java

I have this array here that takes strings values this is my Puzzle Board View,
Right now everything works but the array is hard coded and i need the strings to be generated randomly from 0-4.
I have tried to get a random char and put it is as a string but this didn't work. Any tips would be nice.
Random rand = new Random();
char c = (char)(rand.nextInt(5) + '0');
StringBuilder sb = new StringBuilder();
sb.append(c);
String[] debug_board_state = new String[7];
debug_board_state[0] = "0,3,0,0,3,0,2";
debug_board_state[1] = "1,0,2,0,0,1,2";
debug_board_state[2] = "0,2,0,0,0,0,0";
debug_board_state[3] = "0,0,3,0,3,0,4";
debug_board_state[4] = "2,0,0,0,0,1,0";
debug_board_state[5] = "0,1,0,0,1,0,2";
debug_board_state[6] = "2,0,3,0,0,2,0";
UPDATE.
Thanks to user Answer i was able to get the random matrix, although i ran into another problem, I need do more stuff to the matrix so i don't want to print it out. here is the code
static private final int WIDTH_EASY = 7;
protected void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
};
for (int i = 0; i < WIDTH_EASY; ++i) {
StringTokenizer tokenizer = new StringTokenizer (debug_board_state[i][i], ",");
int column = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
getCurrentState().board_elements[i][column] = new BoardElement();
getCurrentState().board_elements[i][column].max_connecting_bridges = Integer.parseInt(token);
getCurrentState().board_elements[i][column].row = i;
getCurrentState().board_elements[i][column].col = column;
if (getCurrentState().board_elements[i][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[i][column].is_island = true;
}
++column;
}
}
}
The string Tokenizer works with 1d array but not with 2d, i need something that will do the same thing as StringTokenizer and apply it to the matrix. I am getting the following error
java.lang.NullPointerException: Attempt to read from field Island_and_Bridges.Hashi.BoardElement[][] Island_and_Bridges.Hashi.BoardState$State.board_elements on a null object reference

Although I think int[][] is a better idea, here is the String[][] solution. You can use String.valueOf(rand.nextInt(5)) to generate element in the matrix:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String[][] matrix = new String[7][7];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Update:
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}

Something like this?
Pseudo-code:
String[][] debug_board_state = new String[7][7];
for (int x = 0; x < debug_board_state.size(); x++) {
for (int y = 0; y < debug_board_state[x].size(); y++) {
debug_board_state[x][y] = new_random_character();
}
}

0-4 lies from 49 to 52 on the ASCII scale:
Random rand = new Random();
char c = (char)(rand.nextInt(4)+49);
StringBuilder sb = new StringBuilder();
sb.append(c+'0');

Maybe, you want something like this:
public void initBoard() {
Random random = new Random();
String[][] board = new String[7][7];
for (int i=0; i < board.size(); i++) {
for (int j=0; j < board[].size(); j++) {
board[i][j] = String.valueOf(random.nextInt() % 5);
}
}
}
It will initialize your board with random number of String.

Related

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

Switch Rows and Columns 2d Array

I want to swap Columns and Rows in a 2D array.
My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.
Id like to know how I can save the Variable oldField independent
public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
// a Field
int[][] oldField = pField.clone();
int[][] newField = pField.clone();
for (int i = 0; i < newField.length; i++) {
for (int j = (newField.length - 1); j >= 0; j--) {
newField[i][(newField.length - 1) - j] = oldField[j][i];
}
}
return newField;
}
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
this code solves your problem:
public class SwapRowsAndColumns {
public static void main(String[] args) {
int[][] someMatrix = new int[2][3];
someMatrix[0][0] = 1;
someMatrix[0][1] = 2;
someMatrix[0][2] = 3;
someMatrix[1][0] = 4;
someMatrix[1][1] = 5;
someMatrix[1][2] = 6;
printMatrix(someMatrix);
int[][] invertedMatrix = swapMatrix(someMatrix);
printMatrix(invertedMatrix);
}
private static int[][] swapMatrix(int[][] pField) {
int originalTotalRows = pField.length;
int originalTotalColumns = pField[0].length;
int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];
for(int i=0; i< originalTotalRows; i++){
for(int j=0; j < originalTotalColumns; j++){
newMatrix[j][i] = pField[i][j];
}
}
return newMatrix;
}
private static void printMatrix(int[][] matrix){
int totalRows = matrix.length;
int totalColumns = matrix[0].length;
for(int i=0; i< totalRows; i++){
for(int j=0; j< totalColumns; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
}

How to generate random number and export it as JSON?

I was planning to generate a random number and export it as JSON using json-simple. I have the following code
public class Main implements JSONAware{
private final int data;
public Main(int data){
this.data = data;
}
public String toJSONString(){
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(data);
sb.append("]");
sb.append(",");
return sb.toString();
}
public static void main(String[] args){
JSONArray da = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
// da.add("%d",grid[row][col]);
da.add(grid[row][col]);
}
// System.out.println();
}
System.out.println(da);
}
This prints as following:
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...]
but I was trying to print it as
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...],
[68,48,40,44,47,85,8,43,17,78,35,7,77,26,80,34,19,47,17,0,59,5,79,...],
.
.
.
can anyone tell me how would I split the row from column?
As far as I understood your problem, You want 128 rows to be separate JsonArray i.e. 1 row = 1 JsonArray.
For that you could do :
public static void main(String[] args){
JSONArray jArray = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
jArray.add(da);
}
System.out.println(jArray);
}
Just use Json api provided with javaee. And it will be easily accomplished. You will not need to create any jsonToString(...).
import javax.json.Json;
import javax.json.JsonObject;
...
public static void main(String ...args) {
JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
Random generator = new Random();
int[][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (int col = 0; col < 14; col++) {
grid[row][col] = generator.nextInt(100);
arrayBuilder.add(grid[row][col]);
}
jsonBuilder.add(Integer.toString(row), arrayBuilder.build());
}
JsonObject json = jsonBuilder.build();
System.out.println(json);
}
Well if you dont want to use javaee's json api, In your code :
JSONObject obj=new JSONObject();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
obj.put(Integer.toString(row), da);
}
System.out.println(obj);

Bingo Card Game Issue With Repeating Random Integers

I have this static method created for a Bingo game.
public static void bingoCard(){
int [][]card = new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
// First row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][0] = tmp;
valid = false;
}
// Second row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][1] = tmp;
valid = false;
}
// Third row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][2] = tmp;
valid = false;
}
card[2][2] = 0; // The 3rd matrix to the left and right is a 0.
// Fourth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][3] = tmp;
valid = false;
}
// Fifth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][4] = tmp;
valid = false;
}
// Creates an array to make title
String title[] = {"B","I","N","G","O"};
for(int i = 0; i < title.length;i++){
System.out.print(title[i] + "\t");
}
System.out.println();
for(int row = 0; row < card.length; row++){
for(int col = 0; col < card[row].length; col++){
System.out.print(card[row][col] + "\t");
}
System.out.println();
}
}
In the output, this piece of code outputs to this console bingo card: http://puu.sh/487mz/939c8d7a59.png
My main issue is that repeating digits. I am interested in knowing how to get rid of the repeating digits within the 5x5 arrays. Thank you!
Second EDIT: I am also interested in having the game play by itself. Meaning, it would pull out random numbers and correspond to whether or not the digits are on the board. If the condition is met for a BINGO condition, then do something. Does anyone have suggestions in regards to this?
When I've written BINGO boards, I have made an ArrayList containing all possible unique values, then made a call to Collections.shuffle( mylist) which will randomly re-order the values. Then you can iterate over the list to populate your matrix.
Just make sure you re-shuffle for each new board you make
One solution would be to have another data structure that holds all random numbers that have been generated and added into the 2D array that represents the card.
After creating a random number you could check to see if that number already exists in the data structure. If it does then generate a different number. If it doesn't then add it to the card and the data structure.
An ArrayList would be good to use here since it has a nice contains method already written for you. Here's an example.
import java.util.ArrayList;
int [][]card = new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][0]= tmp;
valid = false;
}
Also in all of your nested for loops you never use the variable col. You could simply get rid of the inner for loop in each of these nested loops.
for(int row=0; row < card.length; row++){
for(int col=0; col < card[row].length; col++){
card[row][0]=(int)(Math.random()*15)+1;
}
}
Could be changed to
for(int row=0; row < card.length; row++){
card[row][0]=(int)(Math.random()*15)+1;
}
Also card[2][2]=0; only needs to happen once, here you're setting it multiple times. This could be changed from
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
card[row][2]=(int)(Math.random()*15)+31;
card[2][2]=0;
}
}
To
for(int row=0;row<card.length;row++){
card[row][2]=(int)(Math.random()*15)+31;
}
card[2][2]=0;
Don't use the random function like that - instead, fill up an array or ArrayList with all of the potential random numbers. Then randomly remove numbers from that - that will ensure that you cannot get repeated numbers, as only one of each exists.
Fill an ArrayList with numbers from 1 to N, then use a java.util.Random to pick/remove numbers (shuffle is not necessary):
ArrayList<Integer> card = new ArrayList<Integer>(N);
for (int i = 0; i < N; i++)
card.add(i + 1);
Random random = Random();
int pick = card.remove(random.nextInt(card.size()));
You could easily wrap this into a class to organize things.
Here's the way I would have implemented it.
int[][] board = new int[5][5];
ArrayList<Integer> list = new ArrayList<Integer>();
int number = 0;
int index = 0;
int increment = 1;
int col = 0;
//Run a loop until you're at your last column.
while (col < board.length) {
//Ensure uniqueness of your numbers
while (list.size() < 5) {
number = (int) (Math.random() * 15) + increment;
if (!list.contains(number))
list.add(number);
}
//Add elements to the array.
for (int i : list)
board[index++][col] = i;
//Set values for the next iteration.
index = 0;
increment += 15;
list.clear();
col++;
}
board[2][2] = 0;
//Print the board.
System.out.println("B\tI\tN\tG\tO\n");
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
System.out.print(board[i][j] + "\t");
System.out.println("");
}
Results:
B I N G O
9 29 34 59 62
8 23 44 52 64
7 16 0 53 63
1 19 33 46 71
15 17 41 58 61
Create a class which represents a bingo table. Populate an array with numbers from 0 to 99. When generating a new table, shuffle this array and pull numbers from it in order.
public class BingoBoard{
Integer[] randomNumbers;
int[][] grid = new int[5][5];
public BingoBoard(){
randomNumbers = new Integer[100];
for(int i=0;i<randomNumbers.length;i++)
randomNumbers[i] = i;
populateCard();
}
public void set(int x, int y, int value){
grid[x][y] = value;
}
public void populateCard(){
//randomize the numbers you'll pull from.
//Array.asList will be backed by randomNumbers, so this works.
Collections.shuffle(Arrays.asList(randomNumbers));
for(int x=0;x<5;x++){
for(int y=0;y<5;y++){
int num = randomNumbers[x+y*5];
set(x,y,num);
}
}
}
}
This is a very efficient way to populate your grid with random values.
you could keep a list of visited random numbers generated and check it before adding this number to the game like this
boolean[] visited = new boolean[100];
for(int i = 0; i < 100; i ++) visited[i] = false;
and inside each loop use this
for(int row=0; row < card.length; row++){
int num = (int)(Math.random()*15)+1;
if visited[num]{
row --;
continue;
}
visited[num] = true;
card[row][0] = num;
}
Its simple, just use this.
int element = 5;
List<Integer> numbers = new ArrayList<Integer>(element);
for (int i = 1; i <= element * element; i++)
numbers.add(i);
Collections.shuffle(numbers);
int[][] numArr = new int[element][element];
for (int i = 0, counter = 0; i < element; i++)
for (int j = 0; j < element; j++, counter++)
numArr[i][j] = numbers.get(counter);
for (int i = 0; i < numArr.length; i++) {
for (int j = 0; j < numArr[i].length; j++) {
System.out.printf("%-5d", numArr[i][j]);
}
System.out.println();
}

how to get int[][] dimensionArray?

I want to get matrix[i][j] to my int[][] gettwodimensionalArray, I try so many way, but when I do the test, my gettwodimensionaArray still not store from matrix[i][j]. Please help me out, thank you.
Here is my code look like.
public int[][] gettwodimensionalArray(String file_name) {
File file = new File(file_name);
ArrayList<int[]> rows = new ArrayList<int[]>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] s = line.split("\\s+");
int[] row = new int[s.length];
for (int i = 0; i < s.length; i++) {
row[i] = Integer.parseInt(s[i]);
}
rows.add(row);
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int numbOfRow = rows.size();
// find number of columns by gettting the lenght of one of the rows row
int keepTrackSizeFirstRow;
for (int i = 0; i < numbOfRow; i++) {
if (i == 0) {
keepTrackSizeFirstRow = rows.get(0).length;
}
// compare current row i's array length, to keetracksizefirstrow
}
int[][] matrix = new int[numbOfRow][rows.get(0).length];
// System.out.println(matrix);
for (int i = 0; i < numbOfRow; i++) {
// i = row
for (int j = 0; j < rows.get(i).length; j++) {
// j = col
matrix[i][j] = rows.get(i)[j];
System.out.print(matrix[i][j]);
}
}
return matrix;
}
Not sure what you are trying to do. If you want each row of the input to fit in the array, you can declare the array with variable sizes, like this:
int[][] matrix = new int[numbOfRow][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new int[rows.get(i).length];
}
If instead you want all rows to have the same length, you should find the maximum length of the input like this:
int maxlength = 0;
for (int i = 0; i < rows.size(); i++) {
maxlength = (rows.get(i).length > maxlength) ? rows.get(i).length : maxlength;
}
int[][] matrix = new int[numbOfRow][maxlength];

Categories

Resources