Processing the rows of a 2D array of ints - java

thanks in advance for your help. I'm new to java and I've been having difficulty processing the rows of a 2D array of ints. I've searched through this forum and other resourceful places, but nothing was helpful enough.
Here are the array elements:
1 2 3 4
4 9 17 26
2 4 6 8
1 3 5 7
9 12 32 33
4 8 10 16
3 7 9 21
10 11 12 13
here is my incorect code:
for (int row=0; row<list.length; row++) {
for (int col=0; col<list[row].length; col++) {
if (list[row][0] + 1 != list[row][1] &&
list[row][1] + 1 != list[row][2] &&
list[row][2] + 1 != list[row][3]) {
System.out.print(list[row][col] + " ");
}
}
System.out.println()
I need a code that can test and print the rows of the array whose elements are NOT consecutively incremented by 1, such as 1 2 3 4 and 10 11 12 13, assuming you do not know the values of the elements of the array.

You can iterate through the whole column, compare each value, and use a boolean to keep track if they're consecutively incremented or not. Something like this:
boolean rowIsConsecutive;
int previousValue;
for (int row = 0; row<list.length; row++)
{
rowIsConsecutive = true;
previousValue = list[row][0]; // This will blow up with a 1D array. Just wrote it like this for readability.
for (int col = 1; col<list[row].length && rowIsConsecutive; col++)
{
if (list[row][col] == previousValue + 1)
{
previousValue = list[row][col];
}
else
{
rowIsConsecutive = false;
}
}
if (rowIsConsecutive)
{
System.out.println(Arrays.toString(list[row]));
}
}
Disclaimer: I didn't test this, but something along these lines should work. And I leave it to you to come up with a more performant way to do it :)

Related

Print integer in 4 rows and 4 column Java without Array

I am supposed to create a program that prints out the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Here's my current code:
int n = 1,
cols = 4,
rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n+" ");
n++;
}
System.out.println();
}
But the output is as below:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Can someone please help to figure out the solution for this one? I've tried many ways but just can't get the output right. Thanks anyway.
Java can only print in lines and not in columns. So the first line you need to print is:
1 5 9 13
In other words, every successive number is 4 greater than the number preceding it. So start your outer loop with the first number of the first row, i.e. 1 (one). Now each row contains 4 numbers, so your inner loop needs to iterate four times. See the below code:
int rows = 4;
int cols = 4;
for (int row = 1; row <= rows; row++) {
for (int col = 0; col < cols; col++) {
int number = row + (col * cols);
System.out.print(number + "\t");
}
System.out.println();
}
Running the above code produces the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Change inner loop to go from 0 to cols-1 rather than 1 to cols, and make it print outer loop variable + (inner loop variable * 4).
This will surely work:
for(int row=1, num; row<=4; row++)
{
num = row;
for(int col=1; col<=4; col++, num+=4)
{
System.out.print(num + " ");
}
System.out.println();
}

Looping though an array in java spliting the elements

So I have an array in java that looks like this:
int[] theArray = {2,3,6,9,10,12,17,16,18,20,23,24,28,30,31};
Desired output:
2 3 6 9 10
12 17 16 18 20
23 24 28 30 31
for(int i =0;i<theArray.length;i++)
{
if(i%5==0 && i!=0)
{System.out.println();
}
System.out.print(theArray[i]+" ");
}
All you have to do is go through the array one by one, and use System.out.print to print the elements for each set of 5 elements. Once you have printed 5 elements, do a system.out.println("");
So, basically you want to output the values in an array with a newline after every fifth element? You can use the modulo operator to achieve that.
In (untested) code:
for (int i = 0; i < arrayWithNumbers.length; i++)
{
if (i % 5 == 0 && i != 0) // end of the line
{
System.out.println(arrayWithNumbers[i]);
}
else
{
System.out.print(arrayWithNumbers[i]);
}
}

Java Looping Arrays

How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);

Organizing 2D Interger Arrays in Java

I need to print out the following data using a multi-dimensional array:
5 4 3 2 1
10 9 8 7 6
15 14 13 12 11
20 19 18 17 16
25 24 23 22 21
The programming language that I am using is Java. This is what I have so far:
public class Problem3 {
public static void main(String[] args) {
int[][] prob3 = new int[5][5];
for(int row = 0; row < prob3.length; row++){
System.out.println();
for(int col = 0; col < prob3[row].length; col++){
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}
}
}
When I print this to the screen I get this:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
I am not sure how to manipulate the numbers so they display how I want them. I really want to understand how this works. Let me know if I am doing this completely wrong. Thanks for the help in advance.
If you want iterate through the columns backward, you have to set you start value of the column-loop to the last index, check whether it's still bigger or equal to 0 and decrease col every iteration.
Like that:
int[][] prob3 = new int[5][5];
for (int row = 0; row < prob3.length; row++) {
System.out.println();
for (int col = prob3[row].length - 1; col >= 0; col--) {
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}

I need help producing a pyramid with a certain algorithm to combine numbers (nested loops)

I have the layout for the pyramid set I just can't find out how I would combine or mathematically get the next few numbers. What I need is:
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
My code right now is:
int x = 7;
for (int i =1; i<=x; i++) {
for (int j =1; j<=x-i; j++) {
System.out.print(" ");
}
for (int k=1; k<=i;k++) {
System.out.printf("%2d",k);
}
for(int k=i-1; k>=1;k--) {
System.out.printf("%2d",k);
}
System.out.println(" ");
}
But my output comes out as:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
Sorry if this came out weird; this is my first question ever on this site. How can I modify my code to get the other pyramid?
Firstly, I presume you are trying to compute a Pascal triangle and that when you wrote that the desired output was:
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
you actually mean:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
because otherwise it doesn't make much sense.
Assuming you have made a slight error and the second triangle is the one you want then that is a Pascal's triangle. The rules for computing a Pascal triangle is to add the number above and to the left with the number above and to the right to find the new value.
Image credit Hersfold
You can quite easily write a recursive function that will do this. With a recursive function a good approach is to write your guards and base case, then recurse. This would look like:
private static int calculatePascalNumber(int row, int column)
{
if (row < 1 || column < 1 || column > row) {
return 0;
} else if (column == 1 || row == column) {
return 1;
} else {
return calculatePascalNumber(row - 1, column - 1) +
calculatePascalNumber(row - 1, column);
}
}
These are the rules for this function
if the row or column is less than 1 or the column is wider than the
row these are points outside of the triangle and should return 0
if the column is in one of the end columns (either column equals 1 or the row and column are equal) return 1
otherwise add the two numbers above to the left and the right
You could then call this function within your code that would look like
int x = 7;
for (int row = 1; row <= x; row++) {
for (int j =1; j<=x-row; j++) {
if (j % 2 == 0) {
System.out.print(" ");
} else {
System.out.print(" ");
}
}
for (int column=1; column<=row;column++) {
System.out.printf(" %2d", calculatePascalNumber(row, column));
}
System.out.println(" ");
}
I have revised it a little for formatting, if you wanted to put in further work the ouput formatting would be a good thing to look at.
Finally, it is worth noting performance. If you wanted to run this to compute values on large triangles the number of recursive calls would start making this function go very slowly. A possible way to resolve this would be to cache the results of calls to calculatePascalNumber so that when it is called with parameters it has already computed it returns the value from a hashmap/ array rather than running through all the computations multiple times.
Another option to speed this up for larger triangles is to use this function for calculating a row by itself which could lead to the following code for calculatePascalNumber
private static int calculatePascalNumber(int row, int column)
{
if (row < 0 || column < 0 || column > row) {
return 0;
} else if (column == 1) {
return 1;
} else {
return (calculatePascalNumber(row, column - 1)
* (row + 1 - column)) / (column - 1);
}
}
but what you gain with efficiency you lose with clarity.

Categories

Resources