Setting a specific element in a 2d array to a random value - java

I am looking to set a random value to a certain element in a 2d array.
In my assignment I have to assign a random number 1-5 for the first element in the 2d array and then go the the next row and do the same thing. This is what I have so far but it does not look right.
double CURRENT_BOARD [5][5] = {{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}};
public double shuffleBoard (double currentBoard) {
Random rand = new Random();
shuffledBoard [][] = new double [5][5];
for (i=0 ;i<5 ;i++) {
j = rand.nextInt(5) + 1;
shuffledBoard = shuffledBoard [j][0];
}
return shuffleBoard;
}//shuffleBoard
My end goal is that the elements of the array will look something like
{5, 0, 0, 0, 0}
{3, 0, 0, 0, 0}
{4, 0, 0, 0, 0} and so on as long as the first element of the array is selected at random. Can anyone offer any help to make this happen?

Your declaration of a 2D double array is not correct.
Take a look at this StackOverflow answer
Declaration should be like
double[][] CURRENT_BOARD = new double[][]{{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}};
For random number part, you can try this
public double[][] shuffleBoard(double[][] currentBoard) {
double[][] shuffledBoard = currentBoard;
Random rand = new Random();
double rangeMin = 1, rangeMax = 5;
for (int i = 0; i < 5; i++) {
double j = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();
shuffledBoard[i][0] = j;
}
return shuffledBoard;
}

Related

How do I enter data from user input into a 2D array in Java?

I have a 2D array that needs it's values to be changed based on user input.
private static double nursesArray[][] = {
{2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
The program revolves around it asking the user for the base wage in the year 2020 for the second column (index 1). The program will then ask the user to enter the percent differences in each of the years below, going down each row in that same column. This process needs to be iterated in each of the columns all the way to the end.
The way I have the rest of my code set up is that it uses the array as an argument for the method.
public class nursesUnion {
private static double nursesArray[][] = {
{2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
}
...
I really have no idea where to begin for this. Java is a new language for me and I haven't fully wrapped my head around it yet.
Assuming user already knows how many values they need to enter, you can start with this basic verion:
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
int rows = nursesArray.length;
int columns = nursesArray[0].length;
for (int row = 0; row < rows; row++) {
System.out.println("Please, enter values for year " + nursesArray[row][0]);
// starts with 1 to skip the year.
for (int column = 1; column < columns; column++) {
nursesArray[row][column] = inp.nextDouble();
}
}
}
It just iterates trough rows and columns from left to right, from top to bottom.
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
for(int column = 1; column < arr[0].length; column++){
System.out.println("Enter base wage for col:"+column);
arr[0][column]=inp.nextInt();
System.out.println("Enter % increase per year");
int increase=inp.nextInt();
for(int row=1; row<arr.length; row++){
arr[row][col] += arr[row-1][column]*increase/100;
}
}
}

The code where I use StringBuilder (example:builder.append,builder.replace) giving me a compile error. Everything else is ok

I am trying to write a sudoku "solver" and netbeans is giving me 3 error messages relating to StringBuilder. I had different files for each class but it wouldn't compile then either. Every site i have visited has suggested the way I am doing it. Please help.
public class Sudoku {
public static void main(String[] args) {
int[][] mainpuzzle =
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 81; i++) {
builder.append("09123456789"); // 11
}
for (int j = 0;j < 9; j++ ) {
for ( int k = 0;k < 9;k++ ) {
if ( mainpuzzle [j][k] != 0 ) {
String replace1 = String.valueOf(mainpuzzle[j][k]);
builder.replace((j*11) + (k*11), (j*11) + (k*11),
replace1);
}
}
}
GetSquareCandidates getSqCandid = new GetSquareCandidates();
StringBuilder builderMarkup = new StringBuilder();
builderMarkup = getSqCandid(builder);
}
}
class GetSquareCandidates {
public StringBuilder GetSquareCandidates(StringBuilder boxPassed)
StringBuilder boxRet = new StringBuilder();
boxRet = boxPassed;
return boxRet;
}
}
Looking at your code, there are a couple of things missing like below
GetSquareCandidates class's GetSquareCandidates method does not have an open curly brace.
getSqCandid(StringBuilder builder) method not defined in your GetSquareCandidates class.
Other than these, please share compilation error messages.
There are only a few errors please find below:
Case 1. If public StringBuilder GetSquareCandidates(StringBuilder boxPassed) is a constructor then it can't return.
Case 2. If it is method then kindly do below changes:
Call the method using builderMarkup = getSqCandid.GetSquareCandidates(builder);
Add { after public StringBuilder GetSquareCandidates(StringBuilder boxPassed).
It is recommended using method name like getSquareCandidates().

Efficient way to trim 2d array in Java

I have a following 2 dimensional array:
int[][] array = new int[][]{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0}
};
and I would like to trim all the surrounding zeroes, so my output would be like this (removing "zeros" outside and preserving the zeroes that are surrounded by "ones"):
{0, 1, 1, 1, 0},
{0, 1, 1, 1, 1},
{1, 1, 0, 1, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 1},
{0, 1, 1, 1, 1},
{0, 0, 0, 1, 0}
I'm looking for an efficient way of doing this.
Possible solution (dunno if it is the most efficient way):
public static int[][] trim(int[][] mtx, int rmin, int rmax, int cmin, int cmax) {
int[][] result = new int[rmax-rmin+1][];
for (int r = rmin, i = 0; r <= rmax; r++, i++) {
result[i] = Arrays.copyOfRange(mtx[r], cmin, cmax+1);
}
return result;
}
public static int[][] trim(int[][] mtx, int trimmed) {
int cmin = mtx[0].length;
int rmin = mtx.length;
int cmax = -1;
int rmax = -1;
for (int r = 0; r < mtx.length; r++)
for (int c = 0; c < mtx[0].length; c++)
if (mtx[r][c] != trimmed) {
if (cmin > c) cmin = c;
if (cmax < c) cmax = c;
if (rmin > r) rmin = r;
if (rmax < r) rmax = r;
}
return trim(mtx, rmin, rmax, cmin, cmax);
}
public static void main (String[] args) {
int[][] array = new int[][]{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0}
};
int[][] trim = trim(array, 0);
System.out.println(Arrays.deepToString(trim));
}

Checking for number repetition in a line or column in a grid

I have to make a Sudoku board and have the grid but am confused as how to check for any repetitions across a line or column. The code for my grid is.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grid[i][j] = new JTextField();
BoardPanel.add(grid[i][j]);
So basically i want to check for repetition across i and then down j
Here is the code with an example to show it.
This program will tell if there are two equal numbers in vertical and horizontal bars.
public static void main(String args[]) {
// store your puzzle in puzzle variable.
int puzzle[][] = {
{0, 9, 0, 0, 0, 0, 0, 0, 8},
{0, 0, 3, 2, 0, 7, 0, 9, 0},
{0, 6, 0, 0, 0, 0, 7, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 6},
{0, 0, 5, 4, 3, 2, 1, 0, 0},
{4, 0, 0, 7, 0, 0, 0, 0, 0},
{0, 0, 7, 0, 0, 0, 0, 3, 0},
{0, 2, 0, 9, 0, 8, 6, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 4, 0}
};
testHorizontal(puzzle);
testVertical(puzzle);
}
public static void testHorizontal(int[][] puzzle) {
for (int[] arr : puzzle) {
test(arr);
}
}
public static void testVertical(int[][] puzzle) {
int[] cols = new int[puzzle.length];
for (int i = 0; i < puzzle.length; i++) {
for (int j = 0; j < puzzle.length; j++) {
cols[j] = puzzle[i][j];
test(cols);
}
}
}
public static boolean test(int arr[]) {
boolean flag = false;
for (int a : arr) {
for (int b : arr) {
if (a == b) {
flag = true;
System.out.println("equal numbers found.");
break;
}
}
}
return flag;
}

Depth First Traversal and Adj Matrix

I'm trying to do a depth first traversal. I have no idea if I'm even close. Right now it's printing 1 3 4 5. It should be printing 1 2 4 7 3 5 6. Any help or advice is appreciated. Thanks. :)
Class:
public class myGraphs {
Stack<Integer> st;
int vFirst;
int[][] adjMatrix;
int[] isVisited = new int[7];
public myGraphs(int[][] Matrix) {
this.adjMatrix = Matrix;
st = new Stack<Integer>();
int i;
int[] node = {1, 2, 3, 4, 5, 6, 7};
int firstNode = node[0];
for (i = 1; i < node.length - 1; i++) {
depthFirst(firstNode, node[i]);
}
}
public void depthFirst(int vFirst, int n) {
int v, i;
st.push(vFirst);
while (!st.isEmpty()) {
v = st.pop();
if (isVisited[v]==0) {
System.out.print("\n"+v);
isVisited[v]=1;
}
for ( i=1;i<=n;i++) {
if ((adjMatrix[v][i] == 1) && (isVisited[i] == 0)) {
st.push(v);
isVisited[i]=1;
System.out.print(" " + i);
v = i;
}
}
}
}
//
public static void main(String[] args) {
// 1 2 3 4 5 6 7
int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
new myGraphs(adjMatrix);
}
}
If you are looking at Depth First Traversal then following is the code changes you should make
1) First declare your node array as int[] node = {0, 1, 2, 3, 4, 5, 6}. This should be done to avoid array index start (which is 0 ) and your node start number (which is 1). SO here now we assume that new names of your node 1 is 0, node 2 is 1......and node 7 is 6.
2) Instead of doing
for (i = 1; i < node.length-1; i++){
depthFirst(firstNode, node[i]);
}
in myGraphs do :
depthFirst(firstNode, 7);
3)In depthFirst instead of for ( i=1;i<=n;i++) use for ( i=0;i<n;i++) While doing System.out.println in function depthFirst add one to the number as 0 represents node 1, 1 represents node 2 and so on.
Below is your fully functional code I modified :
import java.util.Stack;
public class DFS {
Stack<Integer> st;
int vFirst;
int[][] adjMatrix;
int[] isVisited = new int[7];
/**
* #param args
*/
public static void main(String[] args) {
int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
new DFS(adjMatrix);
}
public DFS(int[][] Matrix) {
this.adjMatrix = Matrix;
st = new Stack<Integer>();
int i;
int[] node = {0, 1, 2, 3, 4, 5, 6};
int firstNode = node[0];
depthFirst(firstNode, 7);
}
public void depthFirst(int vFirst,int n)
{
int v,i;
st.push(vFirst);
while(!st.isEmpty())
{
v = st.pop();
if(isVisited[v]==0)
{
System.out.print("\n"+(v+1));
isVisited[v]=1;
}
for ( i=0;i<n;i++)
{
if((adjMatrix[v][i] == 1) && (isVisited[i] == 0))
{
st.push(v);
isVisited[i]=1;
System.out.print(" " + (i+1));
v = i;
}
}
}
}}
A working/tested solution in C#, if someone looking for it.
using System;
using System.Collections.Generic;
namespace GraphAdjMatrixDemo
{
public class Program
{
public static void Main(string[] args)
{
// 0 1 2 3 4 5 6
int[,] matrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
bool[] visitMatrix = new bool[matrix.GetLength(0)];
Program ghDemo = new Program();
for (int lpRCnt = 0; lpRCnt < matrix.GetLength(0); lpRCnt++)
{
for (int lpCCnt = 0; lpCCnt < matrix.GetLength(1); lpCCnt++)
{
Console.Write(string.Format(" {0} ", matrix[lpRCnt, lpCCnt]));
}
Console.WriteLine();
}
Console.Write("\nDFS Recursive : ");
ghDemo.DftRecursive(matrix, visitMatrix, 0);
Console.Write("\nDFS Iterative : ");
ghDemo.DftIterative(matrix, 0);
Console.Read();
}
//====================================================================================================================================
public void DftRecursive(int[,] srcMatrix, bool[] visitMatrix, int vertex)
{
visitMatrix[vertex] = true;
Console.Write(vertex + 1 + " ");
for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)
{
if (visitMatrix[neighbour] == false && srcMatrix[vertex, neighbour] == 1)
{
DftRecursive(srcMatrix, visitMatrix, neighbour);
}
}
}
public void DftIterative(int[,] srcMatrix, int srcVertex)
{
bool[] visited = new bool[srcMatrix.GetLength(0)];
Stack<int> vertexStack = new Stack<int>();
vertexStack.Push(srcVertex);
while (vertexStack.Count > 0)
{
int vertex = vertexStack.Pop();
if (visited[vertex] == true)
continue;
Console.Write(vertex + 1 + " ");
visited[vertex] = true;
for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)
//for (int neighbour = srcMatrix.GetLength(0) - 1; neighbour >= 0; neighbour--)// To make same as recursive
{
if (srcMatrix[vertex, neighbour] == 1 && visited[neighbour] == false)
{
vertexStack.Push(neighbour);
}
}
}
}
}
}
To make display order of iterative same as recursion, we need to push neighbors in reverse order to stack. Took this logic from Amit answer here

Categories