Math and Arrays - java

I'm new to java and still learning. I am having one heck of a time trying to figure out how to create this program. I have tried multiple ways and spent about 4 hours now trying to get this to work and it still wont outprint what I need it to. I need a 10x5 array with the first 25 digits being the index variable squared and the last 25 digits being the index times 3. What it is outprinting is 5 numbers over and over 10 times. But it's like it is not reading the "next index variable". I get: 0.0, 1.0, 4.0, 9.0, 16.0, 0.0, 1.0, 2.0, 4.0, etc.. Here is what I have so far(please don't rate down, I'm trying hard to learn this!):
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double [10][5];
for (int col=0; col<=9;col++) {
for (int row=0; row<=4;row++) {
alpha[col][row]= Math.pow(row,2);
System.out.println(alpha[col][row]);
}
}
}
}

I believe you're looking for something like this:
public static void main (String[] args) {
double[][] alpha = new double[10][5];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
int index = (5 * i + j);
if (index < 25) {
alpha[i][j] = (index * index);
System.out.println("index(" + index + ")^2 =" + alpha[i][j]);
} else {
alpha[i][j] = (3 * index);
System.out.println("3*index(" + index + ") = " + alpha[i][j]);
}
}
}
}

You need an index variable initialized to zero outside of the loops and incremented (index++) inside the inner loop. Then you can perform the calculations on the index (0-49) rather than the row variable, which keeps looping 0-4. You'll also need a conditional (if statement) that performs one calculation if index is < 25 and a different calculation if index >= 25.

This is just a generalised version, compared to the accepted answer. It will give the same output, though.
public static void main(String args[]) {
double alpha[][] = new double [10][5];
int index = 0;
for (int row = 0; row < alpha.length; row++)
{
for (int col = 0; col < alpha[row].length; col++)
{
if (index < 25)
alpha[row][col] = Math.pow(index, 2);
else
alpha[row][col] = index * 3;
index++;
System.out.println(alpha[row][col]);
}
System.out.println("" + '\n');
}
}

You're always using the row variable to calculate the assignment value, I think you should combine the values of row and col (or maybe use an index as aetheria says), something like this:
double alpha[][] = new double[10][5];
for (int col = 0; col <= 9; col++) {
for (int row = 0; row <= 4; row++) {
if (col < 5) //if column >= 5 that means that you just passed the 25 index
alpha[col][row] = Math.pow(row + (col*row), 2);
else {
alpha[col][row] = Math.pow(row + (col*row), 3);
}
}
}
I couldn't test it (my eclipse is totally crushed) but I think that will give you the idea (probably you will need to play with the "row + (col*row)" part, when one of the variables is 0 it will not fit your needs). Hope this helps, regards.

Related

How to print first five elements of an matrix in Java

My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.

Cant get required output from loop

I am trying to get a certain output pattern from the array but can't seem to get what I'm looking for and now sure why. Link is the desired output. Sorry if formatting is not good. Array size is inputted by the user.
public class A3_Q2 {
int [][] pattern2 = new int[arraySize][arraySize];
number = 1;
int i;
int j;
int newNumber = arraySize-1;
for (i = 0; i < arraySize; i++)
{
if (i == 0)
{
for (j = 0; j < arraySize; j++)
{
pattern2[i][j] = number;
System.out.printf("%3d", pattern2[i][j]);
number++;
}
}
else
{
for(j = 0; j < i; j++)
{
pattern2[i][j] = number + newNumber;
System.out.printf("%3d", pattern2[i][j]);
newNumber++;
}
newNumber = arraySize-1;
while(j < arraySize)
{
pattern2[i][j] = number;
System.out.printf("%3d", pattern2[i][j]);
number++;
j++;
}
}
System.out.println("");
}
Desired Output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
This image shows the out-of-sequence cells highlighted:
There is no need to separately handle specific rows. Value should be calculated with formula that can be applied universally using modulo operator.
This should do the trick:
for (i = 0; i < arraySize; i++) {
for (j = 0; j < arraySize; j++) {
int value = i * arraySize + (j - i + arraySize + 1) % arraySize;
if (value % arraySize == 0) {
value += arraySize;
}
pattern2[i][j] = value;
System.out.printf("%3d", pattern2[i][j]);
}
System.out.println("");
}
As I suggested in my comment, you're trying to do too many things at once, and that makes the logic (and logic errors) very hard to see.
Breaking each part into its own method can make things much easier.
All those loops and conditionals hid that there were only three tasks required:
Create grid.
Fill grid.
Print grid.
public static void main(final String[] args) {
final int arraySize = 5;
int[][] pattern = new int[arraySize][arraySize];
fillPattern(pattern);
printPattern(pattern);
return;
}
That weird non-sequential output means that "fill the grid" is actually too big a task for one method.
Filling a grid normally requires filling each row.
This grid also requires rotating each row's values one to the right...
one more than the previous row, that is.
That has nothing to do with filling a grid with rows, so it's some other method's problem.
(I could have foisted rowStartValue off onto the other method too, come to think of it.)
private static void fillPattern(int[][] pattern) {
final int rowCount = pattern.length;
for (int rowOffset = 0; rowOffset < rowCount; rowOffset++) {
final int[] row = pattern[rowOffset];
// Numbers in grid start at 1, not 0.
final int rowStartValue = rowOffset * row.length + 1;
fillRow(row, rowOffset, rowStartValue);
}
return;
}
fillRow has to produce values and stuff them into row.
Producing the values is easy;
the only tricky part is deciding where to put them.
Picking the destination required only two operators, so I did it here.
Since no one wants to figure out what row[some / weird * math % here] means, I gave the calculation a name by saving it as the rowIndex variable.
If it had been any more complex, I would have moved the work to a rowIndex(...) method instead.
private static void fillRow(int[] row, final int offset, final int value) {
for (int addend = 0; addend < row.length; addend++) {
final int rowIndex = (offset + addend) % row.length;
row[rowIndex] = value + addend;
}
return;
}
Now that the grid is full, printing it is easy:
private static void printPattern(final int[][] pattern) {
for (final int[] row : pattern) {
for (final int element : row) {
System.out.printf("%3d", element);
}
System.out.println();
}
return;
}
Replacing variables like i and j with row and offset helped a lot, too.

For loop within a for loop

So I'm working on for loops and nested for loops. So I need to stick to these as my main functions.
I've gotten stuck on one question. I can think of the logic of how I'd solve it...but I can't figure how I'd do it with for loops/nested for loops.
I've got to print Ascii codes in rows of 10
Example:
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
(from 32-122)
Here's my code so far:
public class chars{
public static void main(String[]args){
for( int j = 32; j < 122; j++){
System.out.print((char)j);
//Once above loop is performed 10*...execute a new line..using a for loop..??
System.out.println();
}
}
}
You're outer loop should control what row you're on, and the inner loop what column. Thus, just the outer loop looks like this (there are 9 rows):
for (int i = 1; i <= 9; i++)
{
System.out.println("");
}
This will print 9 newlines, giving you the 9 rows.
Now, your column logic goes inside, but before the println.
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
char print = (char)((i * 10) + 32 + j);
System.out.print(print);
}
System.out.println("");
}
This utilizes a small math trick to generate the numbers of the sequence. Row 1 = 32 to 41, 2 = 42 to 51, etc.
Note also that this is slightly more verbose than other possible answers because I used nested loops like you asked.
A straight forward approach could be to use an if statement as QuakeCore suggested. the code would come to look something like the following:
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char)j);
if (j % 10 == 1) {
System.out.println();
}
}
}
This leaves for some ugly code when working with the Modulus function in the if condition. The reason for it is that we are starting with the number 32 and incrementing from their, thus we get j % 10 == 1 instead of something nicer such as j % 10 == 0.
But, your question states you wish to solve it with For loop inside a for loop, making me think it's a school task. This can be solved by looking at for loops as functions to be performed within the 2D space. Such that the first for loop is handling the rows, while the inner for loop is handling columns (or y and x space respectively). From this we can solve the problem as follows:
public static void main(String[] args) {
// Increment row/counter by 10
for (int row = 32; row < 122; row += 10) {
for (int col = 0; col < 10; col++) {
System.out.print((char)(row + col));
}
System.out.println();
}
}
The syntax for a for loop is:
for ( initialization ; termination condition ; increment ) body
However, each of those items in italics above is optional. The initialization and increment parts can have multiple components, separated by a comma.
Since you know the total number of characters is a multiple of 10, here's what I would do:
public static void main(String[]args){
for( int j = 32; j < 122; /* don't increment j here */){
// print 10 chars per line
for (int col=0; col<10; col++, j++ /* increment j here instead */) {
System.out.print((char)j);
}
System.out.println();
}
}
Note that if the total number of characters wasn't a multiple of 10, then the inner loop might print some extras, since the outer loop's condition is only checked once every 10 characters.
This will print each char 10 times in a row ( with nested for loops ):
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
// print 10 times the same char in the same line
for (int i=0;i<=10;i++){
System.out.print((char) j);
}
// after 10 char : goto next line
System.out.println();
}
}
do it with for loops/nested for loops
Try this-
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char) j);
if((j-32)%10==0){
System.out.println();
}
}
}
Here the inner condition will take care of changing line when you have printed 10 values
If you must use nested loops, then maybe something like this would work:
int lineLength = 10;
int lineCount = (122 - 32) / lineLength;
for (int line = 0; line < lineCount; line++) {
for (int column = 0; column < lineLength; column++) {
int index = (line * lineLength) + column;
System.out.print((char)(32 + index) + " ");
}
System.out.println();
}

Check to see if two dimensional array Index is empty, if it is not generate a new Index

So I am basically creating a sort of ring toss application. I create a two dimensional array, "Game Board" as you will, populate the board with fifteen prizes in random locations each time the program is run. Then, I am to generate as if somone throws ten rings at the Index and mark where it lands and if it lands on a prize you get that prize if it doesn't you of course don't get any prizes.
Here I am having trouble generating all 15 prizes... I can print some prizes on the board but it never comes out quite at 15...
Here is the class that sets the prizes in random indexes "array" is my two dimensional array and prizes is an ArrayList that contains the prize list...
public static void setPrizes() {
for (int i = 0; i <= 15; i++) {
row = (int) (Math.random() * 5);
col = (int) (Math.random() * 5);
prizes.add("puzzle");
prizes.add("ball");
prizes.add("cash");
item = prizes.get(0 + (int) (Math.random() * 3));
if(array[row][col].equals(" ")){
array[row][col] = item;
}else{
inp = prizes.get(0 + (int) (Math.random() * 3));
array[row][col] = item;
}
}
}
I can not understand why the if statement wont realize that a prize has already been placed there.
I Generated my board like this...
public static String[][] genBoard() {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = " ";
}
}
return array;
}
The Board after the prizes have been generated...
public static void prizeBoard() {
System.out.println("The Board");
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
System.out.print("[" + array[row][col] + "]");
}
System.out.println();
}
}
You seem to have a few errors here:
Firstly you are using a double random and then rounding. Better is using a single Random object and the nextInt method.
Secondly, your for loop uses <= rather than < so it will be called 16 times rather than 15.
Thirdly, in each iteration you generate a location and then store an item there whether it already has one or not - both branches of your if statement assign item to the location. Whenever you generate an overlap you'll just overwrite the current item.
Fourthy, you are adding 3 new prizes in every iteration. Ideally that code would be in a constructor but, at the very least put it outside the loop.
Taking all these into account you would get:
Random rand = new Random();
List<String> prizes = Arrays.asList("puzzle", "ball", "cash");
int itemCount = 0;
while (itemCount < 15) {
row = rand.nextInt(5);
col = rand.nextInt(5);
if (!array[row][col].equals(" ")) {
array[row][col] = prizes.get(rand.nextInt(prizes.size()));
itemCount++;
}
}

Java pyramid of numbers - version 2

I'm reading a book and before I go to next chapter, I want to solve every exercise from current one. I have a problem with creating this output (the number of rows must be between 11 and 20)
I almost have it, even when I think my code is pretty bad and I could get it in less lines.
public class piramide {
public static void main(String args[]){
int max, n;
max = 20;
n=1;
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
System.out.print(x);
x--;
if (x<0) x=9;
}
System.out.print("A"+n+"A");
for (int j=1; j<min; j++){
System.out.print(x2);
x2--;
if (x2<0) x2=9;
}
System.out.println();
n+=2;
}
}
}
This is my current code and this is the output:
0987654321A1A0987654321
21098765432A3A21098765432
432109876543A5A432109876543
6543210987654A7A6543210987654
87654321098765A9A87654321098765
098765432109876A1A098765432109876
2109876543210987A3A2109876543210987
43210987654321098A5A43210987654321098
654321098765432109A7A654321098765432109
8765432109876543210A9A8765432109876543210
The problem I'm having is that the left part of the pyramid should be reversed. For example in the first row it should start at 0 (from the A1A) and finish in 1 but it starts in 1 and finish in 0, any idea how can I turn it to the other side?
Thanks to all of you who helped me ^^.
Oh, and the caps A are just so I could find the number easier in the output.
Have you worked the problem out?
The code will be much easier to understand with a couple changes...
max, min, and especially the single letter variables like n should have names that help describe what they are. This may also help you think about the problem when you don't have to keep in mind what all those random letters mean.
n I will rename to rowIndex
max I will rename to totalRows
min I will rename to columnIndex
Starting with that we have
public static void main(String args[])
{
int totalRows = 20;
int rowIndex = 1;
int columnIndex = 1;
//we look ready to start at row 1, column 1!
}
Now, this section of your code:
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
You are setting min, or, the columnIndex, to start at 11, because that is the "middle" of the pyramid. Then you print out spaces to catch up to the columnIndex.
x = rowIndex - 1;
x2 = rowIndex - 1;
b = columnIndex - 1;
j and b are now like a second and third column index, which is catching up to the actual columnIndex
Look at this example of how your for loop works:
for (int j=1; j <min; j++) { // j = 1;
while (b<max-1) { // 10 < 19
System.out.print(" "); // print space
b++; // b = 11
// 11 < 19
// print space
// b = ...(*skip to the end*) 19
// j = 2
// b is still 19, doesn't print anything
// j = 3, etc.
}
System.out.print(x);
x--;
if (x<0) x=9;
}
In other words, j and b are unnecessary because we already have a columnIndex we can use. Let's do some more renaming of variables.
x I will rename to printValue
x2 will be unnecessary, we only need one printValue, However, I will be adding a totalColumns to the beginning of our main method.
So now our finished code will look like:
public static void main(String args[])
{
int totalRows = 20;
int totalColumns = (totalRows * 2) - 1; //added totalColumns, notice the number of columns increases by two with each row and we start with 1 column.
int rowIndex = 0;//easier for looping to start with zero
int columnIndex = 0;
int printValue = 0;
while (rowIndex < totalRows) // we will want to spin through every row
{
//notice there is no limit to the length of a variable name!
int numberOfValuesInRow = (rowIndex*2) + 1;
int numberOfSpacesToOffsetOnEachSide = (totalColumns - numberOfValuesInRow) / 2;
//Print Spaces before the numbers in this row
for (int i = 0; i < numberOfSpacesToOffsetOnEachSide; i++) //i is commonly used to stand for index in a single for loop
{
System.out.print(" ");
columnIndex++; //keep track of columnIndex so we know when we are at the middle of the columns
}
//Print numbers in this row
for (int i = 0; i < numberOfValuesInRow; i++)
{
if (columnIndex < (totalColumns/2) + 1) { //depending on columnIndex position, increase or decrease printValue
printValue++;
} else {
printValue--;
}
System.out.print(printValue%10); //Print printValue, the % will return the remainder of (printValue/10)
columnIndex++;
}
System.out.println(); //start next line
columnIndex = 0; //reset columnIndex for the next row
rowIndex++;
}
}

Categories