Randomly populating a 2d array - java

I am using Java and working on 5X5 board game(represented as String[][]) and I looking for an efficient way to randomly place 3 "A"'s, 3 "B",s 3 "C"'s, 3 "D"'s on the board.
I thought about using a nested for loop inside of a while loop to go over each slot, and randomly assign letters to 'slots' on the board, but I want to possibly do it in one pass of the board, if there is a good way to randomly place all 15 letters on the board in one pass.
Any suggestions?

You can use an ArrayList to store the letters (and the empty cells, I'm using a dot . so you can recognize it in the output), then use Collections.shuffle() to put elements of the ArrayList in "random" places. Finally assign each letter to the String[][] array:
public static void main(String[] args)
{
String[][] board = new String[5][5];
List<String> letters = new ArrayList<>();
// fill with letters
for (int i = 0; i < 3; i++) {
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
}
// fill with "empty"
for (int i = 0; i < 10; i++) {
letters.add(".");
}
Collections.shuffle(letters);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = letters.get(i*board.length + j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
Output Sample:
C B . . .
A E . E A
. A . D D
C . . . D
B C E . B
Note:
The operation i*board.length + j will generate consequent numbers 0, 1, 2, 3, ... 24 en the nested loop.

One way: create an ArrayList<Character> or of String, feed it the 15 letters, call java.util.Collections.shuffle(...) on the ArrayList, and then iterate over this List, placing its randomized items into your array.
e.g.,
List<String> stringList = new ArrayList<String>();
for (char c = 'A'; c <= 'E'; c++) {
for (int i = 0; i < 3; i++) {
stringList.add(String.valueOf(c));
}
}
for (int i = 15; i < 25; i++) {
stringList.add(null);
}
Collections.shuffle(stringList);
String[][] gameBoard = new String[5][5];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = stringList.get(i * gameBoard.length + j);
}
}
// now test it
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
System.out.printf("%-6s ", gameBoard[i][j]);
}
System.out.println();
}

Related

How can I fill two-dimensional arrayList with one dimensional?

I have a problem that, whenever I try to fill two dimensional arrayList (5x5) with one dimensional, I get index out of bounds exceptions. I guess that's because the square Array doesn't have index 0 value yet, but I don't know how to fix it.
ArrayList<Character> c = new ArrayList<>();
// Copy character by character into arraylist
for (int i = 0; i < finalArray.length(); i++) {
c.add(i, finalArray.charAt(i));
}
ArrayList<ArrayList<Character>> square = new ArrayList<>();
//square.add(new ArrayList<>());
int k = 0;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
square.get(j).add(i, c.get(k));
k++;
}
}
Add a “row” List to the outer List before the inner loop. You are also using the wrong index for square.
int k = 0;
for(int i = 0; i < 4; i++){
square.add(new ArrayList<>()); // Initialize the row
for(int j = 0; j < 4; j++){
square.get(i).add(c.get(k++)); // get(i) not get(j)!
}
}
Note the other simplifications too.
It would be clearer to do this:
int k = 0;
for(int i = 0; i < 4; i++){
List<Character> row = new ArrayList<>();
square.add(row);
for(int j = 0; j < 4; j++){
row.add(c.get(k++));
}
}

Printing two dimensional array in Java

I'm trying to figure out what's wrong with my code for printing the two dimensional array
int[][] container = new int [3][6];
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <== 6; j++) {
System.out.print(contianer[i][j] + " ");
}
}
System.out.println();
<==is not an operator.
Array start from 0 to length - 1
you have a typo in your variable inside the for
System.out.println();must be executed inside the first for not outside.
int[][] container = new int [3][6];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(container[i][j] + " ");
}
System.out.println();
}

Why won't my array print the rest of the columns?

I'm very curious about encryption so I went out and gave myself a little task, to encrypt a message (below in my .txt file). I'm not getting the output I want, I'm only getting the first column. Why's it only printing the first column?
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[5][5];
// fill array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
// print array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
System.out.println(table[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
My .txt file contains:
E5NOWISTHEWINTEROFOURDISCONTENT*
My output is:
E
5
N
O
W
I want my output to be:
E I T W O O D
5 S H I F U I
N E N R S
O T C
W E O
R N
T
E
N
T
This part has an issue
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
You are only filling characters from j=0 to j=5 as your char array is of size 5 (you are retrieving first 5 characters of the line). I am unsure of what are you trying to achieve as a character array with 5X5 is not the answer.
If your txt file has line delimiters, you can make use of them and read each word into a string and have an array of strings.
I am leaving the explanation here as I couldn't make much out the question
That's because you are just iterating along the rows.
In the for loop, table.length moves along the rows (that is vertically), whereas table[0].length will iterate along the columns, that is on a single row (horizontally)
So you may want to change your loop to:
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
//your code here
}
}
Also, you need to have separate counter for your string. Your value of j is limited to the size of your array column length, namely from 0 to 4.
For idea, try this:
String line = in.readLine();
int cnt = 0;
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
while(cnt<line.length()){
table[i][j] = line.charAt(cnt);
cnt++;
}
}
}

Bidimentional Array

Hi all my program consist of an 2 Dimension array,im reading 2 cordinates in a loop and triying to check if those cordinates in the array are alredy been filled with a asterisc,if this is true y want to re-enicialize my array with the default value "-", and if there is not an asterisc in that specified position y want to fill it in with a asterisc,im not sure if im going for the correct aproach.
this is part of my code.
thanks all.
String[][] matrix = new String[5][5];
String asterisc = "*";
String defaultValue = "_";
Scanner sc = new Scanner(System.in);
int a, b;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = defaultValue;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + "|");
}
System.out.println();
}
a = 0;
b = 0;
while (a >= 0 && b >= 0 && a < matrix.length && b < matrix.length) {
a = sc.nextInt();
b = sc.nextInt();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[a][b].equals(asterisc)) {
matrix[i][j] = defaultValue;
} else {
matrix[a][b] = asterisc;
}
}
}
}
There are unfortunately many things wrong with your code.
Also you have not explained what your algorithm is trying to do.
In brief, to set all asterisks to defaults, you can do
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if matrix[i][j].equals(asterisc){
matrix[i][j]=defaultValue;
}
}
System.out.println();
}
But
why are you using a while loop?
Why are you using a scanner?
Why are a and b initialised at zero, yet need to be greater than zero for the loop?
Are you really trying to re-initialise your whole array, every time the (a,b) item is asterisc?
I think it is not true.Suppose you have typed "6 6" in the terminal,then the variable a=6,and b=6,which is greater than the array length,and the program will throw a exception.I think the thing you may want to do can follow this code:
while(true){
a = sc.nextInt();
b = sc.nextInt();
if(a<0||a>matrix.length||b<0||b>matrix.lenght)
break;
}

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Categories

Resources