Hi I'm making an iterative Pascal's triangle in Java. So far everything works great, until number of rows exceed 13. The output becomes faulty. I must be doing something wrong here, please help.
IterativePascal:
public class IterativePascal extends ErrorPascal implements Pascal {
private int n;
IterativePascal(int n) throws Exception {
super(n);
this.n = n;
}
public void printPascal() {
printPascal(false);
}
public void printPascal(boolean upsideDown) {
if (n == 0) { return; }
for (int j = 0; j <= n; j++) {
for (int i = 0; i < j; i++) {
System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
}
}
}
public long binom(int n, int k) {
return (k == 0 || n == k) ? 1 : faculty(n) / (faculty(k) * faculty(n - k));
}
private long faculty(int n) {
if (n == 0 || n == 1) { return 1; }
int result = 1;
for (int i = 2; i <= n; i++) {
result = result * i;
}
return result;
}
}
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
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 4 24 88 221 399 532 532 399 221 88 24 4 1 <----- wrong
1 0 1 5 14 29 44 50 44 29 14 5 1 0 1 <----- wrong
Help would be appriciated, since I'm new with algorithms.
You're reaching number overflow. Because 14! is too big to fill in java long.
The solution will be to use + instead of !.
Keep your triangle as an 2D array and iterate through it. Each cell should be sum of two 'above'.
+---+---+---+---+
| 1 | | | |
| 1 | 1 | | |
| 1 | 2 | 1 | |
| 1 | 3 | 3 | 1 |
+---+---+---+---+
The code will be as it follows:
public static void triangle(int n) {
int[][] triangle = new int[n];
for (int i = 0; i < n; i++) {
triangle[i] = new int[i+1];
}
triangle[0][0] = 1;
triangle[1][0] = 1;
triangle[1][1] = 1;
for (int i = 2; i < n; i++) {
triangle[i][0] = 1;
for (int j = 1; j < triangle[i].length - 1; j++) {
triangle[i][j] = triangle[i-1][j] + triangle[i-1][j+1];
}
triangle[i][triangle[i].length-1] = 1;
}
printArray(triangle);
}
Edit:
As the OP requires recursive solution with binoms, I decided to add solution introducing BigIntegers as it might be the case.
public BigInteger binom(int n, int k) {
return (k == 0 || n == k) ? BigInteger.ONE : faculty(n).divide((faculty(k).multiple(faculty(n - k)));
}
private BigInteger faculty(int n) {
BigInteger result = BigInteger.ONE;
while (!n.equals(BigInteger.ZERO)) {
result = result.multiply(n);
n = n.subtract(BigInteger.ONE);
}
return result;
}
public void printPascal(boolean upsideDown) {
if (n == 0) { return; }
for (int j = 0; j <= n; j++) {
for (int i = 0; i < j; i++) {
System.out.print(binom(j - 1, i).toString() + (j == i + 1 ? "\n" : " "));
}
}
}
Probably the problem is in your computation of the factorial: I'd assume that your int type can hold numbers up to 32 bits, but 13! is larger than that.
You could check whether long can store larger numbers and define result as long.
Related
I'm trying to do a Lotto game where I have to generate a random card and in the first column numbers go from 1-9, second 10-19 all the way to 90. Another rule of the card is that it can only have 5 numbers at random positions in each line and that's what I'm having trouble with.
I've started with this to put numbers in each column:
int[][] numberCard = new int[3][9];
for (int i = 0; i < numberCard.length; i++) {
numberCard[i][0] = randInt(1, 9);
}
for (int j = 0; j < numberCard.length; j++) {
numberCard[j][1] = randInt(10, 19);
}
And then do put 5 numbers in a number position in each line of the array i tried this:
//Five numbers first line
Random random0 = new Random();
int randomLocation = 0;
while (randomLocation < 5) {
int z0 = random0.nextInt(numberCard.length);
int b0 = random0.nextInt(numberCard[0].length);
if (numberCard[z0][b0] > 0) {
numberCard[z0][b0] = 0;
randomLocation++;
}
}
//Five numbers second line
Random random1 = new Random();
int randomLocation1 = 0;
while (randomLocation1 < 5) {
int z1 = random1.nextInt(numberCard.length);
int b1 = random1.nextInt(numberCard[1].length);
if (numberCard[z1][b1] > 0) {
numberCard[z1][b1] = 0;
randomLocation1++;
}
}
And then the same for the third one.
Output:
0 | 18 | 0 | 0 | 46 | 0 | 61 | 72 | 88 |
0 | 18 | 0 | 31 | 0 | 55 | 0 | 0 | 0 |
0 | 0 | 23 | 34 | 45 | 0 | 0 | 0 | 80 |
The problem is that sometimes I get 5 numbers, sometimes 6 and sometimes 4 when sometimes i get the perfect 5 numbers in each line. More frustrating that not working is only working sometimes...
I thought and I think it is because of the random numbers that sometimes repeat themselves so they go to the same index, but then sometimes I have more than the 5 numbers so that makes no sense.
Correct output expected:
0 | 18 | 23 | 30 | 48 | 0 | 0 | 76 | 0 |
0 | 12 | 24 | 0 | 0 | 58 | 61 | 78 | 0 |
1 | 17 | 0 | 0 | 42 | 54 | 0 | 0 | 86 |
Here is the pretty much the same code as before. The cards have become the rows.
public static void lottery() {
System.out.println(" 1 2 3 4 5 6 7 8 9");
System.out.println("---------------------------");
for (int card = 1; card<= 5; card++) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i <= 8; i++) {
int s = i > 0 ? 0 : 1;
numbers.add(ThreadLocalRandom.current().nextInt(i*10 + s,(i+1)*10));
}
Collections.shuffle(numbers);
int[] row = new int[9];
for (int s = 0; s < 5; s++) {
int pick = numbers.get(s);
row[pick/10] = pick;
}
for (int i = 0; i < 9; i++) {
System.out.printf("%3d", row[i]);
}
System.out.println();
}
}
Prints
1 2 3 4 5 6 7 8 9
---------------------------
5 0 0 0 47 0 67 71 81
1 0 22 0 0 55 65 0 88
1 11 0 30 0 58 0 76 0
0 10 24 0 43 0 0 75 88
3 16 0 0 0 0 60 71 81
I think your approach is complicated than it should be. I would recomend to do it like below:
For each row of your 2D-Array, generate a random number between [1 - 90) and put it to the spot where it belongs by dividing the random number with 10 (will give you values [0 - 8]) while checking that that position doesn't have a random value aready assigned. Reapet this 5 times.
public static void main(String[] args) {
int[][] numberCard = new int[3][9];
Random rand = new Random();
for (int i = 0; i < numberCard.length; i++) {
for (int j = 0; j < 5; j++) {
int x = rand.nextInt(89) + 1;
while (numberCard[i][x / 10] != 0) {
x = rand.nextInt(89) + 1;
}
numberCard[i][x / 10] = x;
}
}
//print or do whatever with your numberCard array
for (int[] row : numberCard) {
System.out.println(Arrays.toString(row));
}
}
Sample output:
[0, 0, 24, 0, 40, 55, 0, 71, 86]
[0, 16, 0, 0, 42, 56, 0, 70, 84]
[5, 12, 0, 0, 49, 0, 69, 0, 82]
You can do it like this:
The card consists of 3 rows.
Each row consists of 9 random cells: 5 filled and 4 hollow.
Column ranges: 1-9 first, 80-90 last, x0-x9 others.
No duplicate numbers in every column.
List<int[]> card = new ArrayList<>();
IntStream.range(0, 3)
// prepare a list of cell indices of the row
.mapToObj(row -> IntStream.range(0, 9)
.boxed().collect(Collectors.toList()))
// random order of cell indices
.peek(Collections::shuffle)
// list of 5 random cell indices in the row
.map(list -> list.subList(0, 5))
// fill the cells with random numbers
.map(list -> IntStream.range(0, 9)
// if this cell is in the list, then fill
// it with a random number, otherwise 0
.map(i -> {
int number = 0;
if (list.contains(i)) {
// unique numbers in each column
boolean isPresent;
do {
// [1-9] first, [80-90] last, [x0-x9] others
number = (int) ((i > 0 ? i * 10 : 1)
+ Math.random()
* (i < 8 ? (i > 0 ? 10 : 9) : 11));
isPresent = false;
for (int[] row : card)
if (row[i] == number)
isPresent = true;
} while (isPresent);
}
return number;
}).toArray())
// add this row to the card
.forEach(card::add);
// output
card.stream()
// row of numbers to string
.map(row -> Arrays.stream(row)
.mapToObj(j -> j == 0 ? " " : String.format("%2d", j))
// concatenate cells into one row
.collect(Collectors.joining(" | ", "| ", " |")))
.forEach(System.out::println);
Output:
| 7 | 20 | | | 47 | 53 | | | 86 |
| | | 27 | 38 | | | 63 | 80 | 85 |
| 4 | | 26 | | | | 69 | 77 | 81 |
I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.
1 2 3
4 5 6
7 8 9
this is my normal array, but i need to make it diagonally like this
1 2 4
3 5 7
6 8 9
this is very stupid way to make it work, but even it is not working because i am not able to find 2nd column elements.
for (i = 0; i < arr.length; ++i) {
for (n = 0; n < arr[0].length; ++n) {
if (i == 0 && n == 0){
arr[i][n] = 0;
} else if (i == 0 && n == 1) {
arr[i][n] = 2;
} else if (i == 1 && n == 0) {
arr[i][n] = 3;
} else if (n == 0) {
arr[i][n] = arr[i - 1][n] - arr[i - 2][n] + 1 + arr[i - 1][n];
} else {
arr[i][n] = arr[i][n - 1] - arr[i][n - 2] + 1 + arr[i][n - 1];
}
}
}
Well, if you were to enumerate the indices in order for that fill pattern, you would get
0,0
1,0
0,1
2,0
1,1
0,2
2,1
1,2
2,2
So, you need to iterate through the total of the two indices. That is, the additive total. As you can see, 0,0 totals 0, 1,0 and 0,1 total 1, and so on. Giving us something like this:
0 1 2
1 2 3
2 3 4
To iterate in this diagonal pattern, we can do the following:
// set up your matrix, any size and shape (MxN) is fine, but jagged arrays will break
int[][] matrix = {{0,0,0},{0,0,0},{0,0,0}};
// number is the value we will put in each position of the matrix
int number = 1;
// iterate while number is less than or equal to the total number of positions
// in the matrix. So, for a 3x3 matrix, 9. (this is why the code won't work for
// jagged arrays)
for (int i = 0; number <= matrix.length * matrix[0].length; i++) {
// start each diagonal at the top row and from the right
int row = 0;
int col = i;
do {
// make sure row and length are within the bounds of the matrix
if (row < matrix.length && col < matrix[row].length) {
matrix[row][col] = number;
number++;
}
// we decrement col while incrementing row in order to traverse down and left
row++;
col--;
} while (row >= 0);
}
Note that while this implementation will work for all matrix sizes (and shapes), it won't be as efficient as possible. Where n is matrix.length (assuming a square matrix), this implementation is an optimal O(n^2) class algorithm in big O notation; however, it effectively performs 2*n^2 iterations, whereas an optimal solution would only perform n^2.
You want to achive something like this:
1 2 4 7
3 5 8 B
6 9 C E
A D F G
In the grid of size NxN, for every point (x,y) in the grid, you can determine the value like this (still needs some corrections for offset at 0, see final formula):
if you are on the upper left half, calculate the area of the triangle that is above and left of you and add your distance from the top
if you are in the lower right half (or on the middle), calculate the area of the triangle below and right of you, add your distance from the bottom and subtract that from the whole area
Let's try it as a formula:
int N = 4; int[][] v = new[N][N];
for(int y = 0; y < N; y++) for(int x = 0; x < N; x++)
v[x][y] = ( x + y < N ) ?
( ( x + y + 1 ) * ( x + y ) / 2 + y + 1 ) :
( N * N + 1 - ( N - y ) - ( 2 * N - x - y - 1 ) * ( 2 * N - x - y - 2 ) / 2 );
I have no idea what complexity this is, but the experts can surely confirm that it is O(N^2) ? Also if it has some cool name like dynamic code, please let me know!
The advantage I see here is that you don't need to jump around memory and can fill all fields with one linear run through the memory. Also having it as a history independent formula can be optimized by the compiler or allow better parallelisation. If you had a machine with N^2 units, they could calculate the whole matrix in one operation.
Diagonal of an M by N Matrix, with Robust Array Formatting
Given that a lot of these answers have already covered the basic N by N arrays, and some are pretty efficient, I went ahead and made a more robust version that handles M by N arrays, along with a nice formatted printer, for your own enjoyment/masochistic viewing.
The efficiency of this method is O(N^2). The format of the printer is O(N^2).
Code
Main
You can set whatever rows and columns you want, assuming positive integer values.
public static void main(String[] args) {
//create an M x N array
int rows = 20;
int columns = 11;
int[][] testData = new int[rows][columns];
//iteratively add numbers
int counter = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
testData[i][j] = ++counter;
}
}
//print our test array
printArray(testData);
System.out.println("");
//print our diagonal array
printArray(diagonal(testData));
}
Printing a 2-Dimensional Array
This method works specifically for this example by determining the number of entries using M x N, and then counting the digits. If you want to, say, display any sized array based on the longest item in the array, you could easily adapt this code to do that. A decent challenge best assigned to the reader. O(N^2) for this, but due to having to search the array for the largest value, one that takes the largest digit will by nature require another O(N^2) for search.
static void printArray(int[][] array) {
//get number of digits
int count = array.length * array[0].length;
//get power of function
int power;
//probably the only time I'd ever end a for loop in a semicolon
//this gives us the number of digits we need
//You could also use logs I guess but I'm not a math guy
for(power = 0; count / Math.pow(10, power) > 1; power++);
for(int i = 0; i < array.length; i++){
System.out.print("{");
for(int j = 0; j < array[0].length; j++){
//Let's say Power is 0. That means we have a single-digit number, so we need
// +1 for the single digit. I throw in 2 to make it extra wide
System.out.print(String.format("%" + Integer.toString(power + 2)
+ "s", Integer.toString(array[i][j])));
}
System.out.println("}");
}
}
The Diagonal Converter
There's a lot of edge cases to be tested for when we account for M x N, so I went ahead and seem to have covered all of them. Not the neatest, but looks to be working.
static int[][] diagonal(int[][] input) {
//our array info
final int numRows = input.length;
final int numColumns = input[0].length;
int[][] result = new int[numRows][numColumns];
//this is our mobile index which we will update as we go through
//as a result of certain situations
int rowIndex = 0;
int columnIndex = 0;
//the cell we're currently filling in
int currentRow = 0;
int currentColumn = 0;
for(int i = 0; i < numRows; i++) {
for(int j = 0; j < numColumns; j++) {
result[currentRow][currentColumn] = input[i][j];
//if our current row is at the bottom of the grid, we should
//check whether we should roll to top or come along
//the right border
if(currentRow == numRows - 1) {
//if we have a wider graph, we want to reset row and
//advance the column to cascade
if(numRows < numColumns && columnIndex < numColumns - 1 ) {
//move current row down a line
currentRow = 0;
//reset columns to far right
currentColumn = ++columnIndex;
}
//if it's a square graph, we can use rowIndex;
else {
//move current row down a line
currentRow = ++rowIndex;
//reset columns to far right
currentColumn = numColumns - 1;
}
}
//check if we've reached left side, happens before the
//top right corner is reached
else if(currentColumn == 0) {
//we can advance our column index to the right
if(columnIndex < numColumns - 1) {
currentRow = rowIndex;
currentColumn = ++columnIndex;
}
//we're already far right so move down a row
else {
currentColumn = columnIndex;
currentRow = ++rowIndex;
}
}
//otherwise we go down and to the left diagonally
else {
currentRow++;
currentColumn--;
}
}
}
return result;
}
Sample Output
Input
{ 1 2 3}
{ 4 5 6}
{ 7 8 9}
{ 10 11 12}
Output
{ 1 2 4}
{ 3 5 7}
{ 6 8 10}
{ 9 11 12}
Input
{ 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 26 27 28 29 30}
{ 31 32 33 34 35 36}
Output
{ 1 2 4 7 11 16}
{ 3 5 8 12 17 22}
{ 6 9 13 18 23 27}
{ 10 14 19 24 28 31}
{ 15 20 25 29 32 34}
{ 21 26 30 33 35 36}
Input
{ 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 26 27 28 29 30}
{ 31 32 33 34 35 36}
{ 37 38 39 40 41 42}
{ 43 44 45 46 47 48}
{ 49 50 51 52 53 54}
{ 55 56 57 58 59 60}
{ 61 62 63 64 65 66}
{ 67 68 69 70 71 72}
{ 73 74 75 76 77 78}
{ 79 80 81 82 83 84}
{ 85 86 87 88 89 90}
{ 91 92 93 94 95 96}
{ 97 98 99 100 101 102}
{ 103 104 105 106 107 108}
{ 109 110 111 112 113 114}
{ 115 116 117 118 119 120}
{ 121 122 123 124 125 126}
{ 127 128 129 130 131 132}
{ 133 134 135 136 137 138}
{ 139 140 141 142 143 144}
{ 145 146 147 148 149 150}
Output
{ 1 2 4 7 11 16}
{ 3 5 8 12 17 22}
{ 6 9 13 18 23 28}
{ 10 14 19 24 29 34}
{ 15 20 25 30 35 40}
{ 21 26 31 36 41 46}
{ 27 32 37 42 47 52}
{ 33 38 43 48 53 58}
{ 39 44 49 54 59 64}
{ 45 50 55 60 65 70}
{ 51 56 61 66 71 76}
{ 57 62 67 72 77 82}
{ 63 68 73 78 83 88}
{ 69 74 79 84 89 94}
{ 75 80 85 90 95 100}
{ 81 86 91 96 101 106}
{ 87 92 97 102 107 112}
{ 93 98 103 108 113 118}
{ 99 104 109 114 119 124}
{ 105 110 115 120 125 130}
{ 111 116 121 126 131 136}
{ 117 122 127 132 137 141}
{ 123 128 133 138 142 145}
{ 129 134 139 143 146 148}
{ 135 140 144 147 149 150}
Luke's intuition is a good one - you're working through down-and-left diagonals. Another thing to notice is the length of the diagonal: 1, 2, 3, 2, 1. I'm also assuming square matrix. Messing with your for indicies can yield this:
int len = 1;
int i = 1;
while(len <= arr.length){
//Fill this diagonal of length len
for(int r = 0; r < len; r++){
int c = (len - 1) - r;
arr[r][c] = i;
i++;
}
len++;
}
len--; len--;
while(len > 0){
//Fill this diagonal of length len
for(int c = arr.length - 1; c > (arr.length - len - 1); c--){
int r = arr.length - len + 2 - c;
arr[r][c] = i;
i++;
}
len--;
}
System.out.println(Arrays.deepToString(arr));
Here is the code translated from here to Java and adjusted to your problem.
int[][] convertToDiagonal(int[][] input) {
int[][] output = new int[input.length][input.length];
int i = 0, j = 0; // i counts rows, j counts columns
int n = input.length;
for (int slice = 0; slice < 2 * n - 1; slice++) {
int z = slice < n ? 0 : slice - n + 1;
for (int k = z; k <= slice - z; ++k) {
// store slice value in current row
output[i][j++] = input[k][slice - k];
}
// if we reached end of row, reset column counter, update row counter
if(j == n) {
j = 0;
i++;
}
}
return output;
}
Input:
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
Output:
| 1 2 4 |
| 3 5 7 |
| 6 8 9 |
Click here for running test code
This is a simple dynamic programming (ish) solution. You basically learn from the last move you made.
NOTE: THIS IS A O(N^2) ALGOIRTHM
Initialize:
int m = 4;
int n = 4;
int[][] array = new int[m][n];;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
array[i][j] = 0;
}
}
The work:
array[0][0] = 1;
for(int i = 0; i < m; i++){
if(i != 0){ array[i][0] = array[i-1][1]+1;}
// This is for the start of each row get 1+ the diagonal
for(int j = 1; j < n; j++){
if(i == 0){
array[i][j] = array[i][j-1]+j;
// only for the first row, take the last element and add + row Count
}else{
if(i == m-1 && j == n -1){
// This is only a check for the last element
array[i][j] = array[i][j-1]+1;
break;
}
// all middle elements: basically look for the diagonal up right.
// if the diagonal up right is out of bounds then take +2 the
// prev element in that row
array[i][j] = ((j+1) != (m)) ? array[i-1][j+1] +1: array[i][j-1]+2;
}
}
}
Printing the solution:
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
System.out.print(array[i][j]);
}
System.out.println("");
}
return 0;
}
You need to do a conversion from index 0..n for x/y (from 0 to x*y) and back to x/y from index...
public void toPos(int index){
return...
}
public int toIndex(int x, int y){
return...
}
I've left the implementation details to you.
Here is Complete working code for your problem. Copy and paste if you like
public class FillArray{
public static void main (String[] args){
int[][] array = {
{1,2,3},
{4,5,6},
{7,8,9}}; //This is your original array
int temp = 0; //declare a temp variable that will hold a swapped value
for (int i = 0; i < array[0].length; i++){
for (int j = 0; j < array[i].length; j++){
if (i < array.length - 1 && j == array[i].length - 1){ //Make sure swapping only
temp = array[i][j]; //occurs within the boundary
array[i][j] = array[i+1][0]; //of the array. In this case
array[i+1][0] = temp; //we will only swap if we are
} //at the last element in each
} //row (j==array[i].length-1)
} //3 elements, but index starts
//at 0, so last index is 2
}
}
I am doing this homework project that produces the pascals triangle but I'm getting an error and I can't find it. I looked it over many times but to me it seems okay, Can someone help me find the bug?
public class PascalsTriangle {
public static void main(String[] args) {
int[][] triangle = new int[11][];
fillIn(triangle);
print(triangle);
}
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.size(); i++) {
triangle[i] = new int[i++];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
}
public static void print(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
I assume you have already changed your code to use length instead of size as the other answer mentions.
When you call this method:
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i++]; // this line
triangle[i][0] = 1;
The line pointed out above should be:
triangle[i] = new int[i + 1];
When you call i++ the int array will be initialized with length i and then i will be incremented. You are already incrementing i in the declaration of your for loop. So, we take away the ++.
But then we have another problem. You start the loop at i = 0. Then you initialize an array with length 0. Then you add an element to that array. Something doesn't make sense. What you meant to do was to initialize the array as int[i + 1].
Finally the program displays some lines from Pascal's 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
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
1 10 45 120 210 252 210 120 45 10 1
not sure this method exist
triangle.size()
try
triangle.length
instead
I need to print the following pattern and i almost did with the coding part.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Following is the program I tried
public class MyPattern {
public static void main(String[] args) {
for (int i = 0; i <= 7; i++) {
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
for (int j = i - 1; j >= 0; j--) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
System.out.print('\n');
}
}
}
When running the program I got the following output
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
But I need the output aligned to left (as specified first). Please help.
Well it's clearly caused by this part of code:
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
Have you tried running it without it?
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
Could also just be, as it does not matter what n is - it will all just do the same.
System.out.print(" " + n);
Comment the line:
//System.out.print(" ");
In the first for loop.
I hope this code helps you understand a few things.
// Make it ready for the loop, no point calling Math.pow() every loop - expensive
import static java.lang.Math.pow;
public class MyPattern {
public void showTree(int treeDepth) {
// Create local method fields, we try to avoid doing this in loops
int depth = treeDepth;
String result = "", sysOutput = "";
// Look the depth of the tree
for( int rowPosition = 0 ; rowPosition < depth ; rowPosition++ ) {
// Reset the row result each time
result = "";
// Build up to the centre (Handle the unique centre value here)
for( int columnPosition = 0 ; columnPosition <= rowPosition ; columnPosition++ )
result += (int) pow(2, columnPosition) + " ";
// Build up from after the centre (reason we -1 from the rowPosition)
for ( int columnPosition = rowPosition - 1 ; columnPosition >= 0 ; columnPosition-- )
result += (int) pow(2, columnPosition) + " ";
// Add the row result to the main output string
sysOutput += result.trim() + "\n";
}
// Output only once, much more efficient
System.out.print( sysOutput );
}
// Good practice to put the main method at the end of the methods
public static void main(String[] args) {
// Good practice to Create Object of itself
MyPattern test = new MyPattern();
// Call method on object (very clear this way)
test.showTree(5);
}
}