2d array table form print out - sorting

so if a user input 9 random numbers
my code prints like this in its sorted form
1 2 3 4 5 6 7 8 9
but I want it to print like a table form
like this
1 2 3
4 5 6
7 8 9
The output after running the code appears as follows:
Please enter number of rows: 3
Please enter number of columns: 3
Please enter 9 numbers to sort: 9 8 7 6 5 4 3 2 1
Sorted numbers:
1 2 3 4 5 6 7 8 9
<emtpy line>
import java.util.Scanner;
public class table
{
public static void main(String args[])
{
System.out.println("Sorted numbers: ");
for(int x = 0; x < matrix.length; x++)
for (int y = 0; y < matrix[x].length; y++)
{
System.out.print(matrix[x][y] + " ");
}
System.out.println(" ");
}
}

Your issue is here:
for(int x = 0; x < matrix.length; x++)
for (int y = 0; y < matrix[x].length; y++)
{
System.out.print(matrix[x][y] + " ");
}
System.out.println(" ");
You didn't enclose your print statement in the outer for loop. If you add brackets, everything in your for loop will execute.
for(int x = 0; x < matrix.length; x++)
{
for (int y = 0; y < matrix[x].length; y++)
{
System.out.print(matrix[x][y] + " ");
}
System.out.println(" ");
}
This way your inner for loop will execute printing all your numbers on a line followed by the println execution and then it repeats.
With this modification, I have arrived at this output:
Please enter number of rows: 3
Please enter number of columns: 3
Please enter 9 numbers to sort: 8 7 6 4 3 1 2 5 9
Sorted numbers:
1 2 3
4 5 6
7 8 9
<empty line>

Related

Gold Mine Problem - Sequence of for loops

Gold mine problem. Following sequence for loop is giving correct result.
//see link for other code
static int getMaxGold(int gold[][], int m, int n) {
//see link for other code
for (int col = n-1; col >= 0; col--) {
for (int row = 0; row < m; row++) {
int right = (col == n-1) ? 0 : goldTable[row][col+1];
int right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1];
int right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1];
goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down));
}
}
}
//see link for other code
While other way round does not give the expected result. For example
for (int col = 0; col < n; col ++) {
for (int row = 0; row < m; row++) {
//same code to calculate right, rightUp and rightDown
}
}
Any explanation for this behaviour?
You don't need to store a whole matrix.
When you build the table, you just need to keep the last layer you processed.
In your recursion, there is diagonally right, or right, so the layer is a column because to compute the value of some cell, you need to know three values (on its right)
You conclude (as spotted by Damien already) that you start from the rightmost column, then to compute the value of every cells of the n-1 column, you only need to know the nth column (which you luckily computed already)
In below example. m_ij refers to i-th line, j-th column. (e.g m_01 == 2, m_10 = 5)
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 3
The last column is {4,8,3,3}
To compute the max value for m_02 you need to choose between 4 and 8
3 - 4
\
8
m_02 = 3 + 8 = 11
To compute the max value of m_12 you need to choose between 4, 8 and 3
4
/
7 - 8
\
3
m_12 = 7 + 8 = 15
Skipping stuff
m_22 = 2 + 8 = 10
m_32 = 6 + 3 = 9
Now you know the max value for each square of the third column
1 2 11 .
5 6 15 .
9 1 10 .
4 5 9 .
You do the same for m_10, m_11, ...
idem
m_01 = 2 + max(11, 15) = 17
m_11 = 6 + 15
m_21 = 1 + 15
m_31 = 5 + 10
Left to process is thus
1 17
5 21
9 16
4 15
Then
1+21
5+21
9+21
4+16
And finally score = max(22, 26, 30, 20)
As you have noticed you only need to keep track of the last processed column. Not a whole table of computation. And the last processed column must start from the right and always be the rightmost one...
I don't think an implem is relevant to help you understand but in case
const s = `
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 3`
const m = s.trim().split('\n').map(x => x.trim().split(' ').map(y => parseInt(y)))
let layer = [0, 0, 0, 0]
for (let j = 3; j >= 0; --j) {
const nextLayer = []
for (let i = 0; i < 4; ++i) {
nextLayer[i] = m[i][j] + Math.max(
layer[i-1] || 0, // we default undefined value as 0 supposing s only holds positive coefficient
layer[i],
layer[i+1] || 0
)
}
layer = nextLayer
}
console.log(Math.max(...layer))

What is the algorithm that is used to generate the numbers in this table and what will be the output for N = 6?

What is the algorithm that is used to generate the numbers in this table and what will be the output for N = 6?
The Table is here:
The first n even numbers including 0 and all integers from n to n+n-1
Output for n = 6 :
0 2 4 6 8 10 6 7 8 9 10 11
C Code Snipplet:
#include <stdio.h>
int main(void) {
printf("Number Sequence Sample \n");
int limit = 6;
for(int i= 0; i <= limit; i++){
printf ("[ %d ] ", i);
if(i == 0){
printf ("%s \n","");
continue;
}
for(int j=0; j <=((i*2)-1); j++){
if( j % 2 == 0){
printf ("%d ",j);
}
}
for(int k=i; k <=((i*2)-1); k++){
printf ("%d ",k);
}
printf ("\n");
}
return 0;
}
Output:
Number Sequence Sample
[ 0 ]
[ 1 ] 0 1
[ 2 ] 0 2 2 3
[ 3 ] 0 2 4 3 4 5
[ 4 ] 0 2 4 6 4 5 6 7
[ 5 ] 0 2 4 6 8 5 6 7 8 9
[ 6 ] 0 2 4 6 8 10 6 7 8 9 10 11

Matrix elements combination

There is a m x n array, I need to output each possible combination Of each line's element. For example, for array{{1,2,3},{4,5,6}}, I need to output{{1,4},{1,5},{1,6},{2,4},{2,5},{2,6},{3,4},{3,5},{3,6}}.
I think there should be a m loop to solve this. For the example above, I wrote the code:
int[,] array = new int[,] {{1, 2, 3}, {4, 5, 6}};
for (var i = 0; i < 3; i++)
{
for (var j = 0; j < 3; j++)
{
Console.WriteLine($"{{{array[0, i]},{array[1, j]}}}");
}
}
With m changes, the number of for loop also changes. But m is unknown when I write the code. How can I solve it?
Maintain a list of active combinations c. Initialize c to be the array's first row. Then iterate every additional row and update c. Basically, you augment each of the current combinations with each of the row's items. Here is some pseudo code:
c = array[0]; //read: the first row of the array
for(var i = 1; i < m; ++i) { //iterate all rows
var c_modified = [];
for(var j = 0; j < n; ++j) { //iterate all row entries
for(var k = 0; k < c.length; ++k) { //iterate all entries of c
add c[k].array[i, j] to c_modified; // . represents concatenation
}
}
c = c_modified;
}
This combination of elements (n^m sets) is called Cartesian product. There are ready-to-use functions for its generation in some language libraries
I believe that the simplest code is recursive one.
type
TArr2D = TArray<TArray<Integer>>;
procedure CartesianProduct(const A: TArr2D; Line: Integer; Reslt: TArray<Integer>);
var
i: integer;
begin
if Line > High(A) then
Memo1.Lines.Add(ArrayToString(Reslt)) // output m-element set
else
for i in A[Line] do
CartesianProduct(A, Line + 1, Reslt + [i]); // include element in set
end;
var
A: TArr2D;
n, m, i, j: Integer;
begin
m := 3;
n := 3;
SetLength(A, m, n);
for j := 0 to m - 1 do
for i := 0 to n - 1 do
A[j, i] := j * n + i;
//0 1 2
//3 4 5
//6 7 8
CartesianProduct(A, 0, []);
gives
0 3 6
0 3 7
0 3 8
0 4 6
0 4 7
0 4 8
0 5 6
0 5 7
0 5 8
1 3 6
1 3 7
1 3 8
1 4 6
1 4 7
1 4 8
1 5 6
1 5 7
1 5 8
2 3 6
2 3 7
2 3 8
2 4 6
2 4 7
2 4 8
2 5 6
2 5 7
2 5 8

How to display all number by increment?

i was task to ask a user to enter a number in range from 1 to 15 and after 5 input, i suppose to display all the number that enter by the user.
saying the user enter 2, 3, 4, 5, and 6, this is what i suppose to display:
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
package barChartPrinting;
import java.util.Scanner;
public class barChart {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int getNumber;
for (int counter = 0; counter < 5; counter++){
System.out.println("Enter a numbers in range of 1 to 15: ");
getNumber = keyboard.nextInt();
while (getNumber < 1 || getNumber > 15){
System.out.println("Invalid number!, please re-enter: ");
getNumber = keyboard.nextInt();
}
}
//end of statement here
}
}

Quicksort algorithm with element in the middle as pivot

I had to do this little task where I had to sort an array 'by hand' like quicksort does. There is one specific point (the recursive one) where I am not sure if my solution is
right. Would be nice if anyone could look through this!
Initial sequence: 7 4 6 8 9 1 3 2
Solution (i = left index, x = pivot, j = right index):
[Pivot-index = (i+j)/2]
Sort for positions 0 to 7:
i x j
7 4 6 8 9 1 3 2
(swap 8 and 2)
i j
7 4 6 8 9 1 3 2
i j
7 4 6 2 9 1 3 8
(swap 9 and 3)
i
j
7 4 6 2 3 1 9 8
Sort for positions 0 to 5:
i x j
7 4 6 2 3 1 9 8
(swap 7 and 1)
i j
1 4 6 2 3 7 9 8
(swap 6 and 3)
i
j
1 4 3 2 6 7 9 8
Sort for positions 0 to 3:
i x j
1 4 3 2 6 7 9 8
(swap 4 and 2)
i
j
1 2 3 4 6 7 9 8
Sort for positions 0 to 2:
i x j
1 2 3 4 6 7 9 8
(swap 2 'and' 2)
j i
1 2 3 4 6 7 9 8
Sort for positions 6 to 7 (from first split - not sure here!)
i j
x
1 2 3 4 6 7 9 8
(swap 9 and 8)
j i
1 2 3 4 6 7 8 9
Used code:
public class QuickSort {
public static void sort (int[] a) { // public method
quicksort(a, 0, a.length-1); // starts private method
}
private static void quicksort (int[] a, int left, int right) {
int tmp; // temporary param
int i = left; // left index
int j = right; // right index
int middle = (left + right) / 2; // middle position
int x = a[middle]; // pivot element
do {
while (a[i] < x) i++; // x works as break
while (a[j] > x) j--; // x works as break
if (i <= j) {
tmp = a[i]; // temporary storage
a[i] = a[j]; // a[i] and
a[j] = tmp; // a[j] get swapped
i++;
j--;
}
} while (i <= j);
// all elements on the left side of the array are smaller than
// all elements in the right side of the array
if (left < j) quicksort(a, left, j); // sort left side
if (i < right) quicksort(a, i, right); // sort right side
}
}

Resources