taking out sets of every 3 element from table (java) - java

I would like to take sets of every 3 elements from table, and then use them for some calculations. Let's say that my table is really big, e.g. 1000+ elements.
Tab elements are like like {x1,y1,z1,x2,y2,z2,...}.
I want to take the first three elements, do some calculations with them, take the next three elements, etc.
Here is my code so far:
double x=0;
double y=0;
double z=0;
for (int i =0; i<tab.length; i++)
x= (double)tab[i];
for (int j =0; j<tab.length; j+=2)
y= (double)tab[j];
for (int k =0; k<tab.length; k+=3)
z= (double)tab[k];
deathstar(x, y, z);
This is using only last 3 elements from tab and deathstar is printing calculation made only on last 3 elements. I was playing around with {}, but it didn't give me results that i wanted. Anyone have any solid idea how to take out every 3 elements from my table ? tab is defined outside of this code and is of type int[].
Thank You in advance for any thoughts about given issue.

Lose the increment part of the loop and increment after each element is gotten.
for (int i =0; i<tab.length;) {
X=(double)tab[i++];
Y=(double)tab[i++];
Z=(double)tab[i++];
//do something
}

This will grab three consecutive elements at a time and then do the calculation. Also checkS to make sure it won't go out of bounds.
double x=0;
double y=0;
double z=0;
int j = 1;
int k = 2;
for (int i =0; i<tab.length; i++)
{
if(i + j < tab.length && i + k < tab.length){
x= (double)tab[i];
y= (double)tab[i + j];
z= (double)tab[i + k];
deathstar(x, y, z);
}
}

You're missing a { after the last for, and so deathstar is only called after all loops finished. Better use { for every for-loop. You could find this easily using a Debugger.
Next, you will ask what's wrong with the logic and why yoou don't get the expected result, because now you would get deathstar(x1,y1,z1), deathstar(x1,y1,z2),.... Try the following (note: I'm assuming the length of tab is indeed a multiple of 3):
for(int i = 0; i < tab.length; i += 3) {
x = tab[i];
y = tab[i+1];
z = tab[i+2];
deathstar(x, y, z);
}
This way your code looks much cleaner.

for (int i =3; i<tab.length; i+=3){
tab[i-1]
tab[i-2]
tab[i-3]
}
maybe this approach will help you

Related

loops in a two-dimensional array

import java.util.Random;
public class arrayClass
{
public static void main(String [] args)
{
int [][] array = new int [5][5];
Random gen = new Random();
for(int x = 0; x < array.length; x++)
{
array[x][2]= gen.nextInt(15) + 1;
}
}
}
I know the code is brief but it might be enough for you to understand
Okay so my goal right now is to put random numbers into each cell without "brute forcing" it(so using loops). I was wondering if there is a way to manipulate two variables in a for loop. Also, how could I make it so that the first row will increase one cell when the cells within the row is done in a loop (in this case cell 0 through 4 in one row)
And is there a way to output a specific range of cells?
thanks and sorry I know this might be pretty confusing
I think you really should use a double for loop here:
for (int x=0; x < array.length; x++) {
for (int y=0; y < array[x].length; ++y) {
array[x][y]= gen.nextInt(15) + 1;
}
}
You could use a single for loop to populate the 2D array, but it would require an external loop counter, and in the end would be functionally similar to a double loop.

Understanding the for loop in Java

I'm new to Java.
I can't seem to understand why these two codes produce different outputs.
Please explain this to me.
What is the difference of y<=x; and y<=5;. As you can see the x is 5 too, I don't understand why I get different outputs.
for (int x = 0; x < 5; x++) {
for (int y = 1; y <=x ; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
*****
x****
xx***
xxx**
xxxx*
Code:
for (int x = 0; x < 5; x++) {
for (int y = 1; y <= 5; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
xxxxx*****
xxxxx****
xxxxx***
xxxxx**
xxxxx*
Basically the main difference is this line:
for(int y=1; y<=x; y++)
resp.
for(int y=1; y<=5; y++)
The number of times the loop is executed is different. Namely in the first case it is variable (so the number of 'x' increases), in the second case it is fixed (5 'x' printed each time).
(edit: typo)
xstarts at 0 so the first iteration has the condition y<=0, the second will have y<=1 and so on .. till y<=5
While the second one will have y<=5in every iteration, thats why you get xxxxx in every line.
In the first code you print x times the "x" String in each row.
for(int y=1; y<=x; y++) {
System.out.print("x");
}
BTW, it prints the following (which is different than what you claim in the question):
*****
x****
xx***
xxx**
xxxx*
In the second code you print 5 times the "x" String in each row.
for(int y=1; y<=5; y++) {
System.out.print("x");
}
As you can see the x is = 5 too
No, x iterates from 0 to 4, so in each iteration of the outer for loop, it has a different value.
In your first code your for(int y=1; y<=x; y++) for iterations of outer for loop is -
for(int y=1;y<=0;++y) (for first iteration of outer loop)
for(int y=1;y<=1;++y) (for second iteration of outer loop)
for(int y=1;y<=2;++y) (for third iteration of outer loop)
for(int y=1;y<=3;++y) (for fourth iteration of outer loop)
for(int y=1;y<=4;++y) (for fifth iteration of outer loop)
But in your second code its always -
for(int y=1; y<=5; ++y)
for all iterations of outer for loop.
It is very simple the will run for 5 time times and every itreation its value will be increamented by 1 i.e. from 0 to 4.
So in first loop inner loop will have the condition like this:
for (int y = 1; y <= x; y++) {
System.out.print("x");
}
But since in first loop the value of x is 0 hence it literally means:
for (int y = 1; y <= 0; y++) {
System.out.print("x");
}
But in the last iteartion of outer loop the value of x is 4 hence this is equivalent to:
for (int y = 1; y <= 4; y++) {
System.out.print("x");
}
So it iterates 4 times.
In your first example y is first less than x = 1 and during the next iteration it will be less x= 2 ... Because x values changes with your first for loop.
For the second example however you state that y have to be less than 5 which doesn't change at all.
They are different because in the first case your x varies from 0 to 4 based on :
for(int x=0; x<5; x++)
In the case second case x is fixed at 5.
I have replaced your two inner for loops with a new stringRepeat function. It might be easier to understand this way.
public class ForLoopStarsAndCrosses {
public static void main(String[] args) {
/// the total length ot the x's and stars
final int length = 5;
// start with 1 x until one less than the length (in this case 4)
for(int x = 1; x < length; x++) {
// the number of stars equals the total length minus the number of x's
final int nbStars = length - x;
// add the x's and the stars
final String output = stringRepeat("x", x) + stringRepeat("*", nbStars);
System.out.println(output);
}
System.out.println();
}
/** Repeat the string s n times */
private static String stringRepeat(String s, int n) {
String result = "";
for (int i = 0; i < n; i += 1) {
result += s;
}
return result;
}
}
Firstly, you should understand the difference between value and variable. Value is a constant as you write 5 but variable can be changeable.
For your question, first code and first round:
x = 1, y<= 1 and output: x
for(int y=1; y<=x; y++){
System.out.print("x");
}
but for the second code and first round:
y<=5 so output is: xxxxx
for(int y=1; y<=5; y++){
System.out.print("x");
}
it is very simple.
The purpose of loops (can be for, while, do-while) is that, how many number of times the same set of statements to be executed under a specific condition. "for" is a definite loop where there will be an index starting with an integer, keep increment it until the condition is achieved. "while" is a indefinite loop where there is no index and it will be executed until the condition is achieved. "do-while" is a loop similar to "while", which will be executed atleast once and then validates the condition for the next iteration.
Based on the above details,
for(int x=0; x<5; x++){
for(int y=1; y<=x; y++){
for(int x=0; x<5; x++){
for(int y=1; y<=5; y++){
The diff between these two conditions is that,
First condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with x which is 0 and 1<=0 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x.
Second condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with 5, 1<=5 which is true, this condition is valid and the statements under Y will be executed and the control will go back control of x until y becomes 6 and condition checked is 6<=5 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x
Note: Due to low reputation, I can't add comments and had to contribute this as an answer. Don't downvote this, instead suggest corrections by comment on the same.

Having trouble multiplying two matrices

Sorry,this is a homework problem. I am not good with maths, so I checked out some videos to understand how two matrices are multiplied. I came up with a formula, but I do not know what I am doing wrong? This question has been answered before, but I did not understand. Thank you.
case 3:
System.out.println("THE PRODUCT OF TWO MATRICES ARE: ");
for(i =0; i< arrayList.length; i++){
for(j =0; j< arrayList1.length; j++){
for(k =0; k < arrayList1.length;k++){
multiplication = arrayList[i][k] * arrayList1[k][j] + multiplication;
}
System.out.print(arrayList[i][j]+" ");
}
System.out.println();
}
break;
First of all you should understand that the multiplication of two matrices should result in a matrice (which not appear to be the case with your multiplication variable).
I suppose you have to program the basic implementation. Let's take a look at the following matrices.
A has n rows, and m columns; said to be a matrice n x m.
Similary, B has m rows and p columns (m x p matrice). The multiplication of A x B will give you a matrice n x p.
Note that if you want to do the multiplication A x B, the matrice A must have the same number of columns that the number of rows of the matrice B.
Now each value in the matrice AB (ith row and jth column) is computed as follow:
That said, let's take a look at the Java implementation (which is a pure translation of the mathematical formula).
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int[][] result = new int[matrixA.length][matrixB[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
for (int k = 0; k < matrixB.length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
The result matrice is initialized at the right dimensions. Then the first two nested loop (with indices i and j) will loop through all the elements of elements of the resulting matrice. Then you just need the third loop to compute the sum.
You'd still need to check that the matrices you give as parameters have the correct length.
The algorithm used is pretty naive (O(n3) complexity). If you don't understand it, there's a lot of resources in the web that explains how it works; but that would more a mathematical question than a programming one.
Hope it helps ! :)

Constraint in Choco

I've found a Choco solver as constraint programming software working with Java. I would like to learn it more. I have done some basic example. But now I would like to try something more complex (Pritsker project scheduling alg) and I need your help. In order to progress I have to understand how to put constraints on rows of matrix variable. Exactly I need to keep a sum of rows equal 1 (task starts only once). I have tried it but unsuccessfuly. Could you help? I do use Choco 2.1.5 My matrix is as follows:
int n = 10; // projects
int m = 12; // time horizon in months
IntegerVariable[][] x = new IntegerVariable[n][m];
int i, j;
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
x[i][j] = Choco.makeIntVar("x_" + i +"_" + j, 0, 1, Options.V_ENUM);
model.addVariable(x[i][j]);
}
}
You should define variables as rows and columns first.
Than, you may use this documentation to proceed. Something like this might be helpful:
IntegerVariable[][] rows;
int n; //number of rows
for(int i=0; i<n; i++)
model.addConstraint(eq(sum(rows[i], 1));
To add constraint over the rows, you should transpose the matrix and apply the constraint over the lines :
transposed = ArrayUtils.transpose(x);
for(int i=0; i<n; ++i){
model.sum(transposed[i], "=", 1);
}

Java, drawing e cross

I'm trying to code a method which draws a cross in JAVA. (see the photo for an example).
Here is the example:
Few Questions:
how do I give an array the dimensions via parameter? It seems that Eclipse needs a number instead of variables for the array dimensions. I thought it is possible to give the method a parameter, how big the dimensions of the array should be.
Don't get the idea how to tell the loop which one of the array positions should be an X and which one not.
Here is my code idea so far...it does not really what it should do :) I took "1" instead of "X", so I can do it with an int array.
public void drawCross(int number){
int i,j;
int array[][]=new int[40][40];
for(j=1;j<=number;j++){
for(i=1;i<=number;i++){
if(array[i]==array[j]){
array[i][j]=1;
System.out.print(array[i][j]+" ");
}
}
System.out.print("\n");
}
}
Thank you in advance.
Pete
As this does not really seem homework, the solution
int[][] array = new int[number][number];
for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (i == j || i == number - 1 - j) {
array[i][j] = 1;
}
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
int[][] a is the conventional way. int a[][] is syntactic sugar for C programmers.
In math i normally is the row, and j the column, so switched the for-loops.
Arrays are indexed from 0.
The condition should say whether one is on one of both diagonals, so only concerns the indices i and j.
|| is OR, and && is AND (should you not already know).
As you see, the matrix array is not needed
So:
boolean isOnDiagonal = i == j || i == number - 1 - j;
System.out.print(isOnDiagonal ? "X " : ". "); // if-then-else operator.

Categories

Resources