How to create a matrix using a 2D array - java

I am trying to create a 6x3 matrix that increases by one each time as you iterate over the column first and the row second.
This is the code, which I currently have:
public static void main(String[] arg) {
int[][] mat1 = new int[6][3];
for(int i = 1; i < mat1.length; i++) {
for(int j = 0; j < mat1[i].length; j++) {
mat1[i][j] = i + j;
System.out.print(mat1[i][j] + " ");
}
System.out.println();
}
}
Right now I am getting the output:
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
The desired output is:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
How would I go about doing this?

You want to generate a "sequence" that counts from 0, 1, 2, .. 17.
Your problem is that i+j doesn't generate that sequence.
Therefore:
mat1[i][j] = i + j;
is simply not counting up. A much simpler solution would be this:
mat1[i][j] = overallCounter++;
( and that overallCounter is declared int overallCounter = 0 before the outer for loop ).
side note: and as the comment correctly states: i should start at 0, too. Arrays are 0-based in Java!

The output you get is correct:
On the first iteration, i = 1 and j = 0, so i+j = 1
On the 4th iteration i = 2 and j = 0, so i+j = 2
On the 7th iteration i = 3 and j = 0, so i+j = 3
here is on of the solution for your problem
public static void main(String[] arg) {
int[][] mat1 = new int[6][3];
int counter = 1;
for(int i = 0; i < mat1.length; i++) {
for(int j = 0; j < mat1[i].length; j++) {
mat1[i][j] = counter;
counter++;
System.out.print(mat1[i][j] + " ");
}
System.out.println();
}
}

Related

Generate a number-pattern in Java beginning with different numbers

I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890

I was trying to print the spiral order matrix as output for a given matrix of numbers, but the output result isn't complete. What is causing this?

I was trying to print the spiral order matrix as output for a given matrix of numbers, all seemed fine until I tried to print the output, the code prints the input till the first spiral loop but stops after printing the second loop for the first step. I am confused, what is my mistake.
edit - the loop has to go clockwise.
import java.util.*;
public class SpiralArray{
public static void main (String [] args){
System.out.println("Enter the size of the array");
//Dimensions of array
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
int [][] spiral = new int [r][c];
// elements of array
for (int i = 0; i < r; i++){
for (int j = 0; j < c; j++){
spiral [i][j] = sc.nextInt();
}
}
int row_start = 0;
int row_end = r-1;
int column_start = 0;
int column_end = c-1;
//printing spiral order matrix
while( row_start <= row_end && column_start <= column_end){
//1
for (int col = column_start; col <= column_end; col++){
System.out.print(spiral[row_start][col] + " ");
}
row_start++;
//2
for (int row = row_start; row <= row_end; row++){
System.out.print(spiral[row][column_end] + " ");
}
column_end--;
//3
for (int col = column_end; col >= column_start; col--){
System.out.print(spiral[row_end][col] + " ");
}
row_end--;
//4
for (int row = row_end; row >= row_start; row--){
System.out.print(spiral[row][column_start] + " ");
}
column_start++;
System.out.println();
}
}
}
Output obtained from the code -
Enter the size of the array
3 4
1 2 3 4
5 5 6 7
8 9 10 1
1 2 3 4 7 1 10 9 8 5
5 6 5
edit
expected output
1 2 3 4 7 1 10 9 8 5
5 6

Fill a Matrix with Random Number with no repeat vertically or horizontally

This is more of a logical question . Problem IS:
I need to fill a Matrix with number (1-9) In such a way so that :
No number should repeat in row
No number should repeat in column
Matrix can be from 3X3 to 8X8
Matrix should contain Random numbers not in some particular order
I am not good at putting logic what i have tried is below :
public class RandMatrix {
static int max=8;
static ArrayList<Integer> numbers=new ArrayList<>();
static int[][] arr=new int[max][max];
public static void main(String[] a){
// To fill number
for (int i = 1; i <=9; i++) {
numbers.add(i);
}
// Shuffle number
Collections.shuffle(numbers);
call();
}
public static void call(){
for (int i = 0; i < max; i++) {
for (int j = 0; j <max ; j++) {
for (int k = 0; k <max ; k++) {
int num=numbers.get(k);
if(!isExist(num,i,j)){
arr[i][j]=num;
break;
}
}
}
Collections.shuffle(numbers);
}
}
private static boolean isExist(int num,int row, int col){
for (int i = row; i >=0; i--) {
if(arr[i][col]==num){
return true;
}
}
for (int j = col; j >=0; j--) {
if(arr[row][j]==num){
return true;
}
}
return false;
}
}
When i print the 2-d array i see in some places there is still 0 as value . Seems like my code breaks. at some point there is no random number left which can be filled. Output is something like :
I know my algo is not right i just can not find a way to make it done .
Can i get some help on this.
I've saved and modified some the code a while ago so as to use if I need another time. I think it's for you ;)
import java.util.Arrays;
import java.util.Random;
class Test {
public static void main(String[] args){
int size = 9;
int[][] matrix= new int[size][];
matrix[0] = MatrixOps.createOrderedArray(size, 1);
for(int x=0; x < size; x++) {
matrix[x] = MatrixOps.createOrderedArray(size, 1);
do {
MatrixOps.shuffle(matrix[x]);
} while(! MatrixOps.compare2DArray(matrix[x], matrix, 0, x));
}
MatrixOps.print(matrix);
}
}
class MatrixOps {
public static void shuffle(int[] arr){
Random random = new Random();
for(int x = 0; x < arr.length; x++)
swap(arr, x, random.nextInt(arr.length));
}
public static int[] createOrderedArray(int size, int startValue) {
int[] num = new int[size];
for (int x = 0; x < num.length; x++)
num[x] = x + startValue;
return num;
}
public static boolean compare2DArray(int[] arr1, int[][] arr2, int begin, int end) {
for (int x = begin; x < end; x++)
if (!compareArray(arr1, arr2[x]))
return false;
return true;
}
// https://stackoverflow.com/questions/19648240/java-best-way-to-print-2d-array/41533179#41533179
public static void print(int[][] array) {
for (int[] x: array) {
for (int y: x) {
System.out.print(y + " ");
}
System.out.println();
}
}
private static boolean compareArray(int[] arr1, int[] arr2){
if(arr1.length != arr2.length)
return false;
for(int x=0; x<arr1.length; x++)
if(arr1[x] == arr2[x])
return false;
return true;
}
private static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
Example output:
5 1 7 2 3 8 9 4 6
4 3 1 5 7 9 2 6 8
9 7 3 8 6 2 4 5 1
6 8 4 3 5 7 1 9 2
1 5 8 9 2 6 7 3 4
7 9 2 6 4 1 5 8 3
8 6 9 4 1 5 3 2 7
3 2 6 7 9 4 8 1 5
2 4 5 1 8 3 6 7 9
Define the following matrix during startup:
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8
When you need to create a n X n matrix do the following:
Randomly pick N numbers between 0-8 (without repeats) for row numbers ->R
Randomly pick N numbers between 0-8 (without repeats) for column numbers ->C
The elements of the final matrix will be M[x][y] = O[R[x]][C[y]]
The only problem is that the result is still not totally random. (It cannot generate ALL of the possible solutions.) Although the randomness is mentioned only in the title but not in the 3 requirements...
I think the best approach is to use a randomized backtracking algorithm.
The elements of the matrix are filled, one after the other. For each matrix element, we first enumerate all the remaining integers which can be used (based on the previous elements). Then each of them is tried in a random order untill the first solution is found.
public static void main(String[] args) {
int[][] matrix = getMatrix(7, 0L);
if (matrix != null) {
for (int row = 0; row < 7; ++row) {
for (int column = 0; column < 7; ++column) {
System.out.print(matrix[row][column]);
}
System.out.println();
}
}
}
public static int[][] getMatrix(int size, long seed) {
int[][] matrix = new int[size][size];
Random random = new Random(seed);
if (!backtrack(matrix, size, 0, random))
return null;
return matrix;
}
// returns true when the backtracking could succesfully fill the matrix
private static boolean backtrack(int[][] matrix, int size, int index, Random random) {
if (index == size * size) {
// all elements are filled without conflict
return true;
} else {
// find the row and column of the next element which need to be filled
int column = index % size;
int row = index / size;
// an array which indicates whether the numbers in range [1 - 9] can be used
// canUse[x] encodes whether number (x+1) can be used
boolean[] canUse = new boolean[9];
Arrays.fill(canUse, true);
// check the previous rows and column elements
for (int c = 0; c < column; ++c)
canUse[matrix[row][c] - 1] = false;
for (int r = 0; r < row; ++r)
canUse[matrix[r][column] - 1] = false;
// generate the list of possible entries
List<Integer> possibilities = new ArrayList<Integer>();
for (int i = 1; i <= 9; ++i)
if (canUse[i - 1])
possibilities.add(i);
// backtrack if there are no possible entries
if (possibilities.isEmpty())
return false;
// shuffle the list (to randomly fill the matrix)
Collections.shuffle(possibilities, random);
// enter the number
for (int possiblity : possibilities) {
matrix[row][column] = possiblity;
if (backtrack(matrix, size, index + 1, random))
return true;
}
return false;
}
}
Output:
4139562
1896375
2613857
9357124
6245931
3482619
8761493
Giving it a wild shot, not writing code. But thinking out:
How about start filling numbers column-wise, such that
mat[0][0]=1
mat[1][0]=2
...
mat[8][0]=9
Then when you starting filling the next column, do like:
mat[1][1]=1
mat[2][1]=2
...
mat[8][1]=8
mat[0][1]=9
and so on.
So its precisely filling the numbers sequentially and diagonally.
Using purely randomization to fill the matrix you will need to redo the last part of the result if you reach a dead end.
public static void call(){
int repeats = 0;
for (int i = 0; i < max; i++) {
for (int j = 0; j <max ; j++) {
for (int k = 0; k <max ; k++) {
int num=numbers.get(k);
if(!isExist(num,i,j)){
arr[i][j]=num;
break;
}
}
}
if(containsZero(arr[i]){
i--;
repeats++;
if(repeats > 1000){
i = 0;
repeats = 0;
}
}
Collections.shuffle(numbers);
}
}
private static boolean containsZero(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] == 0){
return true;
}
}
return false;
}
In some cases changing the last row isn't enough to guarantee that the matrix will be filled. That is why I added a counter which will reset the whole matrix if no solution can be found by changing the last row.

Finding the maximum row for each set of rows in 3D array

This is my first time asking a question here,,
Hello i'm new to Java and i'm having some trouble, I want to know how could i store the info that i got from the code in a 3D array so i can find the largest integer within a group of integers (i have a 3D array and i stored this :
**i want the sum for each row which i have and i want the largest number from each sum.
THANK YOU IN ADVANCE
Gr1
8 5 9 8 7
5 6 8 7 6
7 8 4 5 6
9 5 4 6 8
4 7 5 3 6
Gr2
5 7 4 9 3
8 6 3 7 5
5 2 7 3 4
Gr3
6 4 3 7 6
8 7 9 6 9
7 5 6 4 8
5 9 7 6 7
Gr4
3 5 6 4 7
8 8 7 8 9
4 6 8 6 6
This is my code:
public static void getMaxVotes(int[][][] votes, String[][] uniStud, int size, int size1, PrintWriter uniWrite) {
size = size1 - 1;
int sumStud = 0;
for (int i = 0; i < votes[size].length; i++) {
int totalScore = 0;
for (int j = 0; j < votes[size][i].length; j++) {
int[][] storeSumStud = new int[4][j];
totalScore += votes[size][i][j];
}
System.out.println(uniStud[size][i] + " " + totalScore);
}
}
As #JB Nizet, said, you should re-consider your variables naming, stick to conventions.
Your code seems to be largely incomplete and astray from what you apparently want to do, from you comment, you said
I mean finding the row with the maximum integer
, So here's an alternative code for that :
public static void main(String[] args) {
int[][][] votes = new int[1][2][7];
votes[0][0][0] = 1;
votes[0][0][1] = 5;
votes[0][0][2] = 1;
votes[0][0][3] = 6;
votes[0][0][4] = 9;
votes[0][0][5] = 3;
votes[0][0][6] = 1;
votes[0][1][0] = 1;
votes[0][1][1] = 5;
votes[0][1][2] = 1;
votes[0][1][3] = 10;
votes[0][1][4] = 9;
votes[0][1][5] = 3;
votes[0][1][6] = 1;
getMaxVotes(votes);
}
public static void getMaxVotes(int[][][] votes) {
int largestInt = -1;
String largestRowIndex = "";
for (int i = 0; i < votes.length; i++) {
for (int j = 0; j < votes[i].length; j++) {
for (int k = 0; k < votes[i][j].length; k++) {
if (largestInt <= votes[i][j][k]) {
largestInt = votes[i][j][k];
largestRowIndex = "votes[" + i + "][" + j + "][" + k + "]";
}
}
}
}
System.out.println(largestInt);
System.out.println(largestRowIndex);
return;
}
This code prints :
10
votes[0][1][3]
Thanks to everyone who helped , I've finally solved this problem ,,
public static void getMaxVotes(int[][][] votes, String[][] uniStud, int size, int size1, PrintWriter uniWrite) {
int maxRow = 0;
int indexOfMaxRow = 0;
// Get sum of the first row in maxRow
for (int column = 0; column < votes[size].length; column++) {
maxRow += votes[size][0][column];
}
for (int row = 0; row < votes[size].length; row++) {
int totalOfThisRow = 0;
for (int column = 0; column < votes[size][row].length; column++) {
totalOfThisRow += votes[size][row][column];
}
if (totalOfThisRow > maxRow) {
maxRow = totalOfThisRow;
indexOfMaxRow = row;
}
}
System.out.println(" has the maximum sum of " + maxRow);
System.out.println();
}
}

Create a new start in middle of loop

I have to create a new 2D array from these 2 arrays:
CViEbee[][]
1 2 3 4 1 2
2 1 3 2 4 1
Hdeg[]
1 9 9 9 9 1
The new array (QST) uses CViEbee elements that consist in numbers from 1 to 6 (if exist), and then use them to access index in Hdeg. It will look like this:
QST[][]
10 10 9 9 0 0
10 10 9 9 0 0
QST[0][0] = 10 because, CViEbee[0][j]=1 if j=0 and j=4 then
QST[0][0] = Hdeg[0]+Hdeg[4] = 1+9 = 10
QST[0][5] = 0 because, CViEbee[0][j]=6 --> no CViEbee element = 6
QST[1][3] = 9 because, CViEbee[1][j] = 4 if j= 4 then
QST[1][3] = Hdeg[4]= 9
I've tried to write the program but it's still wrong. This is the code:
int y;
double x = 0; //(Hdeg and QST is double)
int i,j,k,l;
for (i = 0; i < 2; i++) {
y = 1;
for (j = 0; j < 6; j++) {
if (CViEbee[i][j] == y) x = x + Hdeg[j];
k = 0;
if(j == 6) {
QST[i][k] = x;
System.out.print(QST[i][k]);
}
}
j = 0;
y++;
x = 0;
}
System.out.println();
Can somebody help me, please :)
Some flaw/problems
the first inner if statement doesn't have a block ({ and } probably missing)
the condition of the second inner if statement will never be true, j can't be 6 at this point
the assignment j=0 near the end is not necessary
you don't need y because it is always equal to i+1
Here is a working solution. Please note, that I changed the names of the array slightly, but you should be able to grab the idea and use it in your code:
int[][] cv = new int[][]{{1,2,3,4,1,2},{2,1,3,2,4,1}};
int[] hd = new int[]{1,9,9,9,9,1};
int[][] q = new int[2][6];
for (int row = 0; row < 2; row++) {
for (int x = 1; x <= 6; x++) {
for (int col = 0; col < 6; col++) {
if (cv[row][col] == x) {
q[row][x-1] += hd[col];
}
}
}
}
for (int[] row:q) {
for (int col:row) {
System.out.print(col + "\t");
}
System.out.println();
}
Not the most efficient solution (requires three nested loops) but at least a starting point ;)
(BTW: you can test it here in ideone)

Categories

Resources