i want setting an array and below is my code
public static void setArray()
{
int i = 5;
int j = 5;
int testarray[][] = new int[i][j];
for(int x = 0;x<i;x++)
{
for(int y=0;y<j;y++)
{
System.out.print("0 ");
}
System.out.println("");
}
}
the result is something like this:
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
if i want to put a number/alphabet beside to let the user know which column, how can i do that ?
Expected Result:
====================
1 2 3 4 5
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need another initial for-loop to print the numbers, then you need to add another print statement within your second for-loop to print the letter for each row:
System.out.print(" ");
for (int x = 0; x < i; x++) { // this prints the numbers on the first row
System.out.print(" " + x);
}
System.out.println();
for (int x = 0; x < i; x++) {
System.out.print((char) ('A' + x) + "|"); // this prints the letters
for (int y = 0; y < j; y++) {
System.out.print("0 ");
}
System.out.println("");
}
0 1 2 3 4
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need to print 1, 2, 3, 4, 5 .. column number of times and print A, B, C, D .. till you reach the number of rows. Try coding it yourself, it's not that difficult (I don't want to provide a ready-made code)
Related
I have an 10x10 array and I am trying to fill it with nested loop
int A[][] = new int [10][10];
So far I have created this -
C = 1;
for (i=0; i<=9; i++)
for (j=9-i; j>=7-i; j--)
if (j>=0) {
A[i][j] = C; C=C+1;
}
And here is the result so far.
But I am trying to create this with two for loops and cannot manage it.
Thank you for any help!
This should do the job:
iterate rows as usual from 0 to 10, set column index to 9 and decrease it
in the inner loop, set the range from i to the Math.max(i - beltWidth + 1, 0) inclusive (beltWidth is the maximal count of non-zero values in a column, in this case it's 3).
final int size = 10;
final int beltWidth = 3;
int A[][] = new int [size][size];
int c = 1;
for (int i = 0, j = size - 1; i < size; i++, j--) {
for (int k = i; k >= Math.max(i - beltWidth + 1, 0); k--) {
A[k][j] = c++;
}
}
for (int[] r : A) {
for (int x : r) {
System.out.printf("%2d ", x);
}
System.out.println();
}
Output
0 0 0 0 0 0 0 6 3 1
0 0 0 0 0 0 9 5 2 0
0 0 0 0 0 12 8 4 0 0
0 0 0 0 15 11 7 0 0 0
0 0 0 18 14 10 0 0 0 0
0 0 21 17 13 0 0 0 0 0
0 24 20 16 0 0 0 0 0 0
27 23 19 0 0 0 0 0 0 0
26 22 0 0 0 0 0 0 0 0
25 0 0 0 0 0 0 0 0 0
Here is my version. I borrowed the nice printf formatting from Alex's answer :)
I just wanted to mention 2 things:
I think it's a bit easier to read if i and j are called y and x
I seem to remember that if you need performance, you need to traverse the array along the x axis, as that is how CPU cache is fetched (at least in theory). That would make the algorithm a bit more complicated, but I guess in this case we are not really concerned with performance so having y in the inner loop is fine :)
int dimension = 10;
int[][] result = new int[dimension][dimension];
int C = 27;
int yOffset = 9;
for (int x = 0; x < dimension; x++) {
for (int y = Math.min(2, yOffset); y >= 0 && yOffset - y >= 0; y--) {
result[yOffset - y][x] = C--;
}
yOffset--;
}
for (int[] y : result) {
for (int x : y) {
System.out.printf("%2d ", x);
}
System.out.println();
}
Output
0 0 0 0 0 0 0 6 3 1
0 0 0 0 0 0 9 5 2 0
0 0 0 0 0 12 8 4 0 0
0 0 0 0 15 11 7 0 0 0
0 0 0 18 14 10 0 0 0 0
0 0 21 17 13 0 0 0 0 0
0 24 20 16 0 0 0 0 0 0
27 23 19 0 0 0 0 0 0 0
26 22 0 0 0 0 0 0 0 0
25 0 0 0 0 0 0 0 0 0
I've been working on a program to implement a DFS in Java (by taking an adjacency matrix as input from a file). Basically, assuming vertices are traveled in numerical order, I would like to print the order that vertices become dead ends, the number of connected components in the graph, the tree edges and the back edges. But I'm not completely there yet. When I run my program, I get the number "1" as output, and nothing more. I've tried debugging certain parts of the DFS class, but I still can't quite figure out where I'm going wrong. Here is my code:
A basic "Driver" class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("sample1.txt"));
scanner.useDelimiter("[\\s,]+");
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
scanner.close();
new DFS(adjMatrix);
}
}
DFS class:
import java.util.Stack;
public class DFS {
Stack<Integer> stack;
int first;
int[][] adjMatrix;
int[] visited = new int[7];
public DFS(int[][] Matrix) {
this.adjMatrix = Matrix;
stack = new Stack<Integer>();
int[] node = {0, 1, 2, 3, 4, 5, 6};
int firstNode = node[0];
depthFirstSearch(firstNode, 7);
}
public void depthFirstSearch(int first,int n){
int v,i;
stack.push(first);
while(!stack.isEmpty()){
v = stack.pop();
if(visited[v]==0) {
System.out.print("\n"+(v+1));
visited[v]=1;
}
for (i=0;i<n;i++){
if((adjMatrix[v][i] == 1) && (visited[i] == 0)){
stack.push(v);
visited[i]=1;
System.out.print(" " + (i+1));
v = i;
}
}
}
}
}
And the matrix from the input file looks like this:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Take a look at this part:
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
First you read a number, input.
Then you read input rows, in each row input columns.
This is your input data:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
What is the first number, that will be read by scanner.nextInt().
It's 0. So the loop will do nothing.
Prepend the number 8 to your input, that is:
8
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Btw, it's a good idea to verify that you have correctly read the matrix.
Here's an easy way to do that:
for (int[] row : adjMatrix) {
System.out.println(Arrays.toString(row));
}
There are several other issues in this implementation:
The number 7 appears in a couple of places. It's actually a crucial value in the depth-first-search algorithm, and it's actually incorrect. It should be 8. And it should not be hardcoded, it should be derived from the size of the matrix.
It's not a good practice to do computation in a constructor. The purpose of a constructor is to create an object. The depth-first-logic could be moved to a static utility method, there's nothing in the current code to warrant a dedicated class.
Fixing the above issues, and a few minor ones too, the implementation can be written a bit simpler and cleaner:
public static void dfs(int[][] matrix) {
boolean[] visited = new boolean[matrix.length];
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
while (!stack.isEmpty()) {
int v = stack.pop();
if (!visited[v]) {
System.out.print("\n" + (v + 1));
visited[v] = true;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[v][i] == 1 && !visited[i]) {
visited[i] = true;
stack.push(v);
v = i;
System.out.print(" " + (i + 1));
}
}
}
}
So I'm making a Grid class. Here is my setCells method:
public boolean setCells(int rows[], int cols[], int vals[]) {
if (rows.length == cols.length && cols.length == vals.length && vals.length == rows.length) {
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < cols.length; j++) {
for (int k = 0; k < vals.length; k++) {
setValue(rows[i], cols[j], vals[k]);
}
}
}
return true;
}
return false;
}
And here's my client code:
public static void main(String[] args)
{
int rows[] = {1,2};
int columns[] = {1,2};
int values[] = {1,2};
Grid grid1 = new Grid(5, 7);
Grid grid2 = new Grid(8);
grid1.displayGrid();
grid2.displayGrid();
System.out.println(grid1.isEmpty());
grid1.setCells(rows, columns, values);
grid1.displayGrid();
Now whenever I use arrays with one element, the method works fine. However, when the arrays have more than one element, it sets four cells to that value instead of just one. Like this:
0 0 0 0 0 0 0
0 2 2 0 0 0 0
0 2 2 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
It's supposed to look like this:
0 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 2 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
Can anybody help me with this?
Your current algorithm has three nested loops, meaning that it attempts to set every possible combination of rows and columns to every listed value, rather than simply setting each cell once as desired. You only need one loop to iterate through a variable tracking index into all three arrays:
if (rows.length == cols.length && cols.length == vals.length) {
for (int i = 0; i < rows.length; i++) {
setValue(rows[i], cols[i], vals[i]);
}
}
Additionally, if you already know that rows and cols have the same lengths, and that cols and vals have the same lengths, then the third check (rows and vals have same length) is not necessary. I've removed it in the example code snippet directly preceding.
I'm trying to get an output of a random string consisted of 1's and 0's in a Matrix style. I know how to display a string consisted of 1's and 0's, but I can't keep on looping through it for some reason. What I'm trying to do, is that whenever the StringBuilder reaches the length of 20, I want to start the loop on a new line again and repeat this 100 times.
import java.util.List;
import java.util.Random;
public class main {
static Random rand = new Random();
static StringBuilder x = new StringBuilder();
static int a = 0;
public static void main(String[] args) {
generatingnumber();
}
public static void generatingnumber() {
for (int bv = 0; bv <= 100; bv++) {
int random = rand.nextInt(50);
if (random % 2 == 0) {
x.append(" 0");
} else {
x.append(" 1");
}
if (x.length() == 20) {
System.out.println(x);
}
}
}
}
public class MatrixFilm {
public static void main(String[] args) {
int rows = 100;
int cols = 20;
for (int count1 = 0; count1 < (rows * cols); count1++) {
for (int count2 = 0; count2 < cols; count2++) {
int randomNum = 0 + (int) (Math.random() * 2);
System.out.print(" " + randomNum);
}
System.out.println();
}
}
}
Result:
0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 1 1 1 1
1 1 0 1 1 1 0 1 0 1 0 1 1 0 1 1 0 0 1 0
0 1 0 0 1 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0
0 1 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 0 1 0
0 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 0 0
....
Your string has length of 20 characters only once. You are not interested in whether x.length() == 20 but if x.length() % 20 == 0.
For a new line you can append "\n" (or "\r\n" for Windows machine) to the string, everytime just before printing it.
Change println to print (which doesn't add new line character at the end of printed string) in order to maintain continuity between prints.
Taking all into account:
if (x.length() % 20 == 0) {
x.append("\r\n");
System.out.print(x);
}
However it still wouldn't be enough, for "\r\n" itself adds to the length of the string. This should work:
if (x.length() % 20 == 0) {
x.replace(x.length() - 2, x.length(), "\r\n");
System.out.print(x);
}
You can also - and it would be better to... - reset the string, as #owlstead has mentioned.
if (x.length() == 20) {
System.out.println(x);
x.setLength(0);
}
Anyway; what I presented is not a solution for the problem. Only solution to - probably improper - approach you have currently taken on it.
So I got this 2D Array that is a 5x5 array and I have to subtract or add 1 to one of the rows that the user chooses to change. All is fine when the user inputs to change the first row, but with the higher rows, for example 2, it adds more than 1.
The array values are
1 -2 1 0 0
-1 0 4 2 0
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
And the method I used to add 1 is the following
public static void plusRow (int i){
for(int row = 0; row < board.length; row++){
int[] rows = board[i];
for(int col = 0; col < board.length; col++){
rows[col] = rows[col] + 1;
System.out.print(board[row][col] + " ");
}
System.out.println("");
}
}
My output value for example with 2 comes out like this
1 -2 1 0 0
1 2 6 4 2
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
When it should be
1 -2 1 0 0
0 1 5 3 1
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
The problem is that your nested for loop runs as many times as the function input int "i"
Your algorithm is very inefficient- you don't need to do a nested loop here. Break your ouput and your math into 2 different loops.
for(int j =0; j<boards[i].length; j++){
boards[i][j] += 1;
}
Then write a double loop to ouput board. In fact, that should be a separate function