I want to randomly generate a symmetrical 10x10 table with "*" symbols but It all basically prints in two long rows. I know I'm doing something wrong but I'm looking at it too hard and cant see the issue.
public class Main {
public static void main(String[]args) {
int n = 10;
char[][] array = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
char value;
if (Math.random()> .5) {
value = '*';
}
else {
value = ' ';
}
array[i][j] = value;
array[j][i] = value;
System.out.print(array[i][j]);
System.out.println();
System.out.print(array[j][i]);
}
}
}
}```
I don't see your context here. But you can try this
public class Main {
public static void main(String[] args) {
int n = 10;
char[][] array = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
char value;
if (Math.random() > .5) {
value = '*';
} else {
value = ' ';
}
array[i][j] = value;
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
you're not printing row by row, also missing the diagonal element. Fixing those and some other minor changes
int n = 10;
char[][] matrix = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
char value = rd.nextBoolean() ? '*':' ';
matrix[i][j] = value;
matrix[j][i] = value;
}
}
for(char[] row : matrix) {
System.out.println(row);
}
Related
The program below ask the user how many mines he wants to see on the field and then display the field with mines.
In next step I need to calculate how many mines are around each empty cell. And I know that I
need to check 8 cells if the cell is in the middle, 5 cells if the cell is in the side, and 3
cells if the cell is in the corner. If there are from 1 to 8 mines around the cell, I need to
output the number of mines instead of the symbol representing an empty cell.
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(minesweeper[i][j]);
}
System.out.println();
}
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
You can do it like this:
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Minesweeper minesweeper = new Minesweeper();
minesweeper.randomX();
minesweeper.printMinesweeper();
}
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(getCharAt(i, j));
}
System.out.println();
}
}
private String getCharAt(int i, int j) {
if (mineAt(i, j)) {
return "X";
}
int minesNear = countMinesNear(i, j);
return Integer.toString(minesNear);
}
private boolean mineAt(int i, int j) {
return minesweeper[i][j] == 'X';
}
private int countMinesNear(int i, int j) {
int mines = 0;
for (int x = -1; x <= 1; x++) {//near fields in x direction
for (int y = -1; y <= 1; y++) {//near fields in y direction
if (x + i >= 0 && x + i < minesweeper.length && y + j >= 0 && y + j < minesweeper.length) {//check whether the field exists
if (minesweeper[x+i][y+j] == 'X') {//check whether the field is a mine
mines++;
}
}
}
}
return mines;
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
The countMinesNear(int, int) method check whether the field near exists (to prevent index errors on the edges) and counts the mines if the fields exist.
Can anyone help me why the calculateCoin function doesn't show up? Basically what it does is, it calculates the coin, that was generated randomly in the drawMap function within 20% chance.
What I did and not sure doing right is, I called the calculateCoin function IN the drawMap function, and then I call the drawMap in the main.
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.drawMap());
}
public int[][] drawMap(){
int[][] map = new int[5][5];
char coin = 'o';
for(int i =0; i<map.length; i++){
for(int j =0; j<map[i].length; j++){
map[i][j] = (int)(Math.random()*10);
if(map[i][j]<2){
System.out.print(coin+ " ");
}
else
System.out.print("*"+ " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public int calculateCoin(int[][] map, char coin){
int result = 0;
for(int i = 0; i<map.length; i++){
for(int j = 0; j<map[i].length; j++){
if(map[i][j] == coin){
result++;
}
}
}
return result;
}
The function is actually being called but the value that you return from it is not stored in any variable. If you want something to happen after printing the map, store the result of the call in a variable and then print it.
int calculatedCoin = calculateCoin(map, coin);
System.out.println("Calculated coin: " + calculatedCoin)
try this , but basically you declare a type of a class not a method.
public class dave {
public static void main(String[] args) {
dave main = new dave();
System.out.println(dave.drawMap());
}
public static int[][] drawMap() {
int[][] map = new int[5][5];
char coin = 'o';
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = (int) (Math.random() * 10);
if (map[i][j] < 2) {
System.out.print(coin + " ");
} else
System.out.print("*" + " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public static int calculateCoin(int[][] map, char coin) {
int result = 0;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == coin) {
result++;
}
}
}
return result;
}
}
I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
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.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
I've created a 2 dimensional array with the same length and it is randomly filled with 1 and 0 for example.
0100
0010
1110
1111
How do I code the program to find the rows,columns and diagonals with all 1s and 0s
This is my code so far:
public class Test2dArray {
public static void main(String[] args) {
int row,column;
System.out.print("Enter the lenghth of matrix:");
Scanner input = new Scanner(System.in);
Random rand = new Random ();
int mSize = input.nextInt();
int [][] mArray = new int [mSize][mSize];
for (row=0; row < mSize; row++){
for(column=0; column < mSize; column++){
mArray[row][column]=rand.nextInt(2);
System.out.print(mArray[row][column]+ " ");
}
System.out.println();
}
}
}
Code isn't perfect (I'm sure it can be optimized) but it works
public static void main (String[] args) throws java.lang.Exception {
int row = 5;
int column = 5;
int [][] mArray = fillArray(row, column);
System.out.println("Rows: " + findRows(mArray));
System.out.println("Columns: " + findColumns(mArray));
System.out.println("Diags: " + findDiags(mArray));
}
private static ArrayList<Integer> findRows(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < mArray.length; i++){
boolean isRow = true;
for(int j = 0; j < mArray[0].length; j++){
if (j > 0 && mArray[i][j] != mArray[i][j - 1]) {
isRow = false;
break;
}
}
if (isRow) result.add(i);
}
return result;
}
private static ArrayList<Integer> findColumns(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j < mArray[0].length; j++){
boolean isColumn = true;
for(int i = 0; i < mArray.length; i++){
if (i > 0 && mArray[i][j] != mArray[i - 1][j]) {
isColumn = false;
break;
}
}
if (isColumn) result.add(j);
}
return result;
}
private static ArrayList<Integer> findDiags(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 1; i < mArray.length; i++) {
boolean isDiag = true;
for (int j = 0; j < i; j++) {
if (mArray[i - j][j] != mArray[i - j - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(i);
}
for (int i = 0; i < mArray.length - 2; i++) {
boolean isDiag = true;
for (int j = i + 1; j < mArray.length - 1; j++) {
if (mArray[mArray.length - j + i][j] != mArray[mArray.length - j + i - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(mArray.length + i);
}
return result;
}
private static int[][] fillArray(int row, int column) {
int [][] mArray = new int [row][column];
Random rand = new Random();
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
mArray[i][j] = rand.nextInt(2);
System.out.print(mArray[i][j] + " ");
}
System.out.println();
}
return mArray;
}
Iterate and for each row and columns and sum the values into rowSum and columSum.
So:
if (rowSum == mSize)
System.out.print("The row "+i+"is full of ones");
if (rowSum == 0)
System.out.print("The row "+i+"is full of zeros");
And the same, obviously, for the columns and diagonals.
How do I make it so that when I output the grid when I run the code, no two numbers or letters will be the same? When I currently run this code I could get 3x "L" or 2x "6", how do I make it so that they only appear once?
package polycipher;
import java.util.ArrayList;
public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];
{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}
private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}
public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}
This should be much faster than validating each random choice:
Store your valid chars into an array;
char[] valid = validChars.toCharArray();
Shuffle the array;
shuffle(valid)
Go through the positions in the matrix, storing the elements in the same order they appear in the shuffled array.
assert (CIPHER_KEY.length * CIPHER_KEY.length) <= valid.length;
int k = 0;
for (int i = 0; i < CIPHER_KEY.length; i++) {
for (int j = 0; j < CIPHER_KEY.length; j++) {
matrix[i][j] = valid[k++];
}
}
Use a set and generate a new random if the old random number is in the map:
Pseudocode:
Set<Integer> set = new HashSet<Integer>();
for () {
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
while (!set.contains(random)){
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
}
//If we exit this loop it means the set doesn't contain the number
set.add(random);
//Insert your code here
}