Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this 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
And this one for rc = 3:
1 2 3
6 4 5
8 9 7
Related
I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
I have a class with a method that transposes an array given the array, rows, and columns
public class Transpose {
public static void main(String[] args) {
int[][] array = new int[6][5];
System.out.println("Original:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] += i+1;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
transpose(array, 6, 5);
}
public static void transpose(int[][] array, int arrayRows, int arrayColumns)
{
int[][] transposedArray = new int[arrayRows][arrayColumns];
System.out.println("Transposed:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
}
The output I get looks like this:
Original:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
Transposed:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I realized that the method only works when the values of arrayRows and arrayColumns are the same value, for example: 6, 6 or 5, 5. I tried to place the values opposite of each other, the rows in columns and vice versa, however it did not work. How can I get the method to work for non-rectangular/square arrays?
See line comments for explanation. Those are the only lines I modified.
public static void transpose(int[][] array, int arrayRows, int arrayColumns) {
int[][] transposedArray = new int[arrayColumns][arrayRows]; //swap number of rows and columns
System.out.println("Transposed:");
for (int i = 0; i < transposedArray.length; i++) { //take the length of transposedArray, not array
for (int j = 0; j < transposedArray[i].length; j++) { //take the length of transposedArray, not array
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
You need to swap the places of arrayRows and arrayColumns in the transposed matrix, because the new matrix is supposed to be a [5][6] instead of a [6][5].
So your line of
int[][] transposedArray = new int[arrayRows][arrayColumns];
becomes
int[][] transposedArray = new int[arrayColumns][arrayRows];
We also need to swap i and j in the following statement, because the loops are following the indices of the original matrix:
transposedArray[i][j] = array[j][i];
to
transposedArray[j][i] = array[i][j];
And lastly, you can't print the transposed matrix while you're creating it as you're doing now, because you're just re-printing the original matrix that way. I suggest printing the matrix after you're done creating it.
With these changes, your code ends up like this:
public static void main(String[] args) {
int[][] array = new int[6][5];
System.out.println("Original:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] += i+1;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
transpose(array, 6, 5);
}
public static void transpose(int[][] array, int arrayRows, int arrayColumns)
{
int[][] transposedArray = new int[arrayColumns][arrayRows];
System.out.println("Transposed:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
transposedArray[j][i] = array[i][j];
}
}
for(int i = 0; i < transposedArray.length; i++) { //print the transposed matrix
for(int j = 0; j < transposedArray[i].length; j++) {
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
You can see a working example here.
for(int i = 0; i < array.length; i++)
// should count the number of rows. = 6
iterating from 0 ... 5
for(int j = 0; j < array[i].length; j++) // should count the number of columns = 5
iterate from 0..4
transposedArray[i][j] = array[j][i];
to access 6 ... you need j=5 ; i = 0...4
your loops are not able to access the values
I added the plus 1 here: for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++)
so that the program would grab all the numbers except the one right before what I mean is..
If I enter 10 for the Maximum x value and 10 for the y (without the plus 1) this is what the output shows:
Would you like a power table or a multiplication table?
Press 1 for Power
Press 2 for Multiplication
2
Maximum x value?
10
Maximum y value?
10
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
I don't know why this wont work please help this is the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int defaulVa = 1;
int defaulEx = 2;
System.out.println("Would you like a power table or a multiplication table?"
+ "\n Press 1 for Power"
+ "\n Press 2 for Multiplicatiion");
int a = sc.nextInt();
System.out.println("Maximum x value?");
int x = sc.nextInt();
System.out.println("Maximum y value?");
int y = sc.nextInt();
switch (a) {
case 1:
System.out.println("How would you like your base?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int answer = sc.nextInt();
switch (answer) {
case 1:
System.out.println("What value?");
int value = sc.nextInt();
powerTable(x, y, value, defaulVa);
break;
case 2:
System.out.println("How would you like your exponent?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int d = sc.nextInt();
switch (d) {
case 1:
System.out.println("What value?");
int d2 = sc.nextInt();
powerTable(x, y, defaulVa, d2);
break;
case 2:
powerTable(x, y, defaulVa, defaulEx);
break;
default:
break;
}
break;
default:
break;
}
break;
case 2:
multiplicationTable(x, y);
break;
default:
System.out.println("I see you can't follow simple instructions...");
System.exit(0);
break;
}
}
public static int[][] powerTable(int arrayDimensionX, int arrayDimensionY, int value, int value2) {
int[][] myArray;
myArray = new int[arrayDimensionX][arrayDimensionY];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray[i].length; j++) {
if (value == 1) {
value = myArray[i][j] = i * j;
} else if (value != 1) {
value++;
}
myArray[i][j] = ((int) Math.pow(value, value2));
}
}
for (int i = 1; i < arrayDimensionX; i++) {
for (int j = 1; j < arrayDimensionY; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return myArray;
}
public static int[][] multiplicationTable(int x, int y) {
int[][] myArray;
myArray = new int[x][y];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
myArray[i][j] = i * j;
}
}
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return null;
}
}
Arrays are 0 indexed (they start at 0 and the last index is length - 1)
I would say...
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Should be...
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
You'd need to change the loop that builds the table to look something more like...
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
myArray[i][j] = (1 + i) * (1 + j); // <-- Modify the indices here instead...
}
}
Have a look at Arrays for more details
Why does your multiplicationTable function have an int[][] return type, when you return null? Would be better to just make it a void function, if you don't plan on having it return the array.
Anyway, since all the function does in print to the screen, the function is over complicated. Could be made much simpler, something like this:
public static void multiplicationTable(int x, int y)
{
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= y; j++)
System.out.print(i * j);
System.out.println();
}
}
But if you want it left as is, your ArrayIndexOutOfBounds exception is likely occuring here:
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Because x and y are the size of the array, making your loop go to i < x + 1 and i < y + 1 will throw the exception, because it is trying to access a non-existing index. If you change it to i < x and i < y it shouldn't throw the exception:
for (int i = 1; i < x; i++) {
for (int j = 1; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
However, even that will not give you the desired output, as it skips the first element of the array, because array indexes start at 0, not 1, meaning the multiplications for 1 will be missing from your table.
This question already has answers here:
Pascal's triangle 2d array - formatting printed output
(5 answers)
Closed 1 year ago.
The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.
public static void triangle(int maxRows) {
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
}
I need to format the values of the triangle such that it looks like a triangle:
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
I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.
public static long pascalTriangle(int r, int k) {
if (r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}
This method allows you to find the k-th value of r-th row.
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
Output:
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
In each row you will need to print:
n spaces
m numbers
n spaces
Your job is to figure out n (which will be zero in the last line) and m based on row number.
[This is more like a comment but I needed more formatting options than comments provide]
You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function
System.out.printf();
Here is a handy reference guide
Also note that you will need to take into account that some numbers are more than 1 digit long!
import java.util.*;
class Mine {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i < n; i++) {
int size = 1;
for (int j = 1; j <= i; j++) {
int a[] = new int[size];
int d[] = new int[size];
for (int k = 1; k <= size; k++) {
a[1] = 1;
a[size] = 1;
for (int p = 1; p <= size; p++) {
d[p] = a[p];
}
if (size >= 3) {
for (int m = 2; m < size; m++) {
a[m] = d[m] + d[m - 1];
}
}
}
for (int y = 0; y < size; y++) {
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int s = 7;
int k = 1;
int r;
for (int i = 1; i <= s; i++) {
int num = 1;
r = i;
int col = 0;
for (int j = 1; j <= 2 * s - 1; j++) {
if (j <= s - i)
System.out.print(" ");
else if (j >= s + i)
System.out.print(" ");
else {
if (k % 2 == 0) {
System.out.print(" ");
} else {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
col++;
}
k++;
}
}
System.out.println("");
k = 1;
}
}
}
Output:
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
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
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
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Code perfectly prints pascal triangle:
public static void main(String[] args) {
int a, num;
for (int i = 0; i <= 4; i++) {
num = 1;
a = i + 1;
for (int j = 4; j > 0; j--) {
if (j > i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
I need help, I got a problem with this matrix, I need to have it in this way:
1 2 3 4 = 10
2 4 6 8 = 20
3 6 9 12 = 30
4 8 12 16 = 40
But I have it in this way:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
I dont know how can we do that, I intent but nothing
This is my code:
public class Matrix {
public static void main(String args[]) {
int mult = 4;
for (int i = 1; i <= mult; i++) {
// System.out.println();
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
System.out.print(operacion + " ");
}
int sum = 0;
sum = i + sum;
System.out.println(sum);
}
}
}
bye
When you do this:
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
suma is always equal to operacion, because you set it to 0 every time and then add operacion.
You want to do this:
int suma = 0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma += operacion;
Put int sum = 0 outside the second for loop.
int suma = 0;
for (int i = 1; i <= mult; i++) {
// System.out.println();
suma =0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma = operacion + suma;
System.out.print(operacion + " ");
}
System.out.println(suma);
}
You should take a look to String.format() or PrintStream.printf(). I think others allready helped you with the sum-problem. So try to print the values out like this:
for (int i = 0; i < 4; i++)
{
int[] values = new int[4];
int sum = 0;
for (int j = 0; j < 4; j++)
{
values[i] = (i+1) * (j+1);
sum += values[i];
}
System.out.printf("%-4d%-4d%-4d%-4d = %d\n", values[0], values[1], values[2], values[3], sum);
}
Try also to remove all the minus signs (-) from the last line and see what you like the most.
You are resetting sum to 0 just before you use it. You probably want for sum to be reset before your inner loop, added to inside your inner loop and printed outside your inner loop.
Also for your final println, print (" = " + sum) instead of just sum.
Trying not to actually correct your code since you mentioned this is an exercise (homework)--and thank you for tagging it. I wish more answerers would look for that sign as an indication that the person needs to learn and doesn't need the answer coded for them.