Create a new start in middle of loop - java

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)

Related

Adding 2 differently sized 2d arrays together

I am trying to add two differently sized matrices together. For example, the resultant matrix should be matOne[0][0]+matTwo[0][0]; however, I am having trouble taking into account their different sizes (if there's a missing value, it should be assumed it's a 0).
Here's my code:
int[][] go(int[][] matOne, int[][] matTwo)
{
int size= Math.max(matOne.length, matTwo.length);
int[][] matThree= new int [size][];
int c;
for (int i=0; i<size; i++) {
c= Math.max(matOne[i].length, matTwo[i].length);
for (int j = 0; j < c; j++) {
if (matOne[j].length > i) {
matThree[i][j] += matOne[i][j];
}
if (matTwo[j].length > i) {
matThree[i][j] += matTwo[i][j];
}
}
}
return matOne;
}
I see the following bugs in the code:
You never allocate the inner arrays. After you get size, you correctly create the outer array. After you get c, you forget to create the inner array for that row.
Right inside the i loop, one of matOne[i] and matTwo[i] is likely to fail eventually, whichever one is shorter.
Variable i iterates over rows, and variable j iterates over columns in a row, which means that the [i][j] in the += statements are correct, but that the matOne[j].length > i should have been matOne[i].length > j. Same for matTwo.
You return the wrong array.
Here is the fixed code, using better variable names:
static int[][] go(int[][] matOne, int[][] matTwo) {
int rows = Math.max(matOne.length, matTwo.length);
int[][] matThree = new int [rows][];
for (int r = 0; r < rows; r++) {
int cells = Math.max((matOne.length > r ? matOne[r].length : 0),
(matTwo.length > r ? matTwo[r].length : 0));
matThree[r] = new int[cells];
for (int c = 0; c < cells; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
Test
public static void main(String[] args) {
int[][] matOne = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] matTwo = { { 7, 8 }, { 9, 10 }, { 11, 12 } };
int[][] matThree = go(matOne, matTwo);
print(matOne);
System.out.println("+");
print(matTwo);
System.out.println("=");
print(matThree);
}
static void print(int[][] mat) {
for (int[] row : mat) {
for (int cell : row)
System.out.printf(" %2d", cell);
System.out.println();
}
}
Output
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12
If you don't want the result to be a jagged array, i.e. you want the result to be a 2D rectangular matrix, change the code as follows:
static int[][] go(int[][] matOne, int[][] matTwo) {
int rows = Math.max(matOne.length, matTwo.length);
int cols = 0;
for (int[] row : matOne)
cols = Math.max(cols, row.length);
for (int[] row : matTwo)
cols = Math.max(cols, row.length);
int[][] matThree = new int [rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
Output
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12 0
Just before the inner loop; replace current calculation of 'c' and allocate a row for matThree.
c = 0;
if (i < matOne.length)
c = matOne[i].length;
if (i < matTwo.length && matTwo[i].length > c)
c = matTwo[i].length;
matThree[i] = new int[c];
The code inside the inner loop should be:
int elem1 = 0, elem2 = 0;
if (i < matOne.length && j < matOne[i].length)
elem1 = matOne[i][j];
if (i < matTwo.length && j < matTwo[i].length)
elem2 = matTwo[i][j];
matThree[i][j] = elem1 + elem2;
Firstly, it's necessary to allocate storage for the current row of matThree.
Secondly, you need to check that both row and column are within bounds for each matrix. For my taste it's clearest to explicitly extract the values, defaulting to zero, thus the variables elem1 and elem2.

How to create a matrix using a 2D array

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();
}
}

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

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();
}
}

how to get specific column in 2D array using java

when searched value exist in array, I choose the column and save them.
for example
1 2 3 4 5 6
A B C D E F
G H I J K L
I want to make a column including x==1||x==4
below column will be result of what i want
1 4
A D
G J
below code is my 2D array code. I make 1D array from csv file and 2D array. when searched value exist, I choose the column and save them.
String str = readCSV(new File("D:/sample_folder/sample1.csv"));
String[] strArr = parse(str); // It comes out in a row in an String array.
int varNumber = 45;
int rowNumber = strArr.length/varNumber;
String[][] Array2D = new String[varNumber][rowNumber];
for(int j=0;j<varNumber;j++)
{
for(int i=0; i<rowNumber;i++)
{
String k = strArr[i*varNumber+j];
Array2D[j][i]= k;
}
} //make 2D array
You can through rows of 2D array and pick the column you want.
for(int j=0;j<rowNumber;j++)
{
// index starts from 0
yourArray[j][0] = array2D[j][0];
yourArray[j][1] = array2D[j][3];
}
Or more dynamically you could write:
int[] columnsYouWant = {0, 3};
for(int j=0;j<rowNumber;j++)
{
for(int c=0;c<columnsYouWant.length;c++)
{
yourArray[j][c] = array2D[j][columnsYouWant[c]];
}
}
If you want to use if (x == 1 || x == 4) :
for(int j=0;j<rowNumber;j++)
{
column = 0;
for(int c=0;c<columnNumber;c++)
{
x = c + 1;
if (x == 1 || x == 4)
yourArray[j][column++] = array2D[j][c];
}
}
I might get it wrong. It also seems you may want to have columns starting with 1 or 4. In that case, if your first row has numbers and rest are alphabetical. You should find the column starting with either 1 or 4.
for(int j=0;j<colNumber;j++)
{
x = array2d[0][j];
if ( x == 1 || x == 4 ) {
// add you j to an array
}
}
In the case you will know which columns you want, and you can use the second piece of code in my answer to create 2D array with columns you want.
Try this simulation, I populate this in your 2DArray:
1 2 3 4 5 6
A B C D E F
G H I J K L
after that, I made a code to print only the columns 1 and 4.
public static void main(String[] args) {
String[][] twoDArray = populateArray();
int x = 0;
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
x = j + 1;
if(x == 1 || x == 4) {
System.out.print(twoDArray[i][j]);
}
}
System.out.println();
}
}
public static String[][] populateArray() {
String[][] twoDArray = new String[3][6];
for (int i = 0; i < twoDArray[0].length; i++) {
twoDArray[0][i] = (i + 1) + "";
}
char alphaChar = 'A';
for (int i = 1; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
twoDArray[i][j] = String.valueOf(alphaChar);
alphaChar++;
}
}
return twoDArray;
}
the output of the code is:
14
AD
GJ
if you comment the if(x == 1 || x == 4) { that I used, it will print like this:
123456
ABCDEF
GHIJKL

Categories

Resources