I'm trying to sort selected column. I have generated array with random numbers. This is my code to print selected column for example I'm trying to select 1st row = min.
int column = 10,
row = 10,
min = 1 ,
max = 9;
for (int i = 0; i < arr.length; i = i + 1) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = (int)(Math.random()*(max - min) + min);
System.out.printf("%2d", arr [i][j]);
}
}
for (int k = 0 ; k < column ; k++) {
System.out.print(arr[min][k]);
}
I have tried doing something like this to sort:
for (int k = 0 ; k < column ; k++) {
for (int j = k + 1 ; j < arr.length; j++) {
if (arr[k][min] > arr[j][min]) {
int[] temp = mas[k];
arr[k] = arr[j];
arr[j] = temp;
}}
System.out.print(arr[min][k]);}
Just use the Arrays#sort() method with a comparator like this (Java8+). Here are examples sorting a specific column in Ascending and Descending order. Only works with a Matrix where all array columns are of equal length as demonstrated:
Ascending Order:
int[][] myInt2DArray = {{2, 1, 4, 6},
{5, 3, 7, 1},
{1, 2, 3, 4},
{6, 9, 2, 8}};
// Sort in Ascending Order based on 4th column (column index 3):
int columnIndexToSort = 3;
// Sort the Array:
Arrays.sort(ary, (a, b) -> a[columnIndexToSort] - b[columnIndexToSort]);
// Display Array in Console:
for (int[] array : myInt2DArray) {
System.out.println(Arrays.toString(array));
}
Output to Console Window (note the fourth data column):
[5, 3, 7, 1]
[1, 2, 3, 4]
[2, 1, 4, 6]
[6, 9, 2, 8]
Descending Order:
// Sort in Descending Order based on 3rd column (column index 2):
columnIndexToSort = 2;
// Sort the Array:
Arrays.sort(ary, (a, b) -> b[columnIndexToSort] - a[columnIndexToSort]);
// Display Array in Console:
for (int[] array : myInt2DArray) {
System.out.println(Arrays.toString(array));
}
Output to Console Window (note the third data column):
[5, 3, 7, 1]
[2, 1, 4, 6]
[1, 2, 3, 4]
[6, 9, 2, 8]
Related
I have a 2d-array data, as an example I choose those numbers:
int[][] data = {
{1, 2, 3, 4},
{1, 2, 3, 4},
{1, 2, 3, 4}};
For each column I want to add the sum of numbers together and save them in seperate integers.
This is the result im looking for:
c_zero = 3;
c_one = 6;
c_two = 9;
c_three = 12;
This is the code I have thus far:
int c_zero = 0;
int c_one = 0;
int c_two = 0;
int c_three = 0;
for (int a = 0; a < data.length; a++) {
for (int b = 0; b < data.length; b++) {
for (int[] row : data)
for (int value : row) {
if (int[] row == 0) { //this does not work
c_zero += value;
}
if (int[] row == 1) { //this does not work
c_one += value;
}
...
}
}
}
How can I get the values for each row in a specific row?
I would create a 1D integer array and use that to store the running sum for each column:
int[][] data = {{1,2,3,4},
{1,2,3,4},
{1,2,3,4}};
int[] colSums = new int[data[0].length];
for (int r=0; r < data.length; ++r) {
for (int c=0; c < data[r].length; ++c) {
colSums[c] += data[r][c];
}
}
System.out.println(Arrays.toString(colSums)); // [3, 6, 9, 12]
Using Java 8, you can apply the reduce method to the stream over the rows of a 2d array to sum the elements in the columns and produce a 1d array of sums.
// array must not be rectangular
int[][] data = {
{1, 2, 3, 4},
{1, 2, 3, 4},
{1, 2, 3, 4, 5}};
int[] sum = Arrays.stream(data)
// sequentially summation of
// the elements of two rows
.reduce((row1, row2) -> IntStream
// iterating over the indexes of the largest row
.range(0, Math.max(row1.length, row2.length))
// sum the elements, if any, or 0 otherwise
.map(i -> (i < row1.length ? row1[i] : 0)
+ (i < row2.length ? row2[i] : 0))
// array of sums by column
.toArray())
.orElse(null);
// output of an array of sums
System.out.println(Arrays.toString(sum));
// [3, 6, 9, 12, 5]
// output by columns
IntStream.range(0, sum.length)
.mapToObj(i -> "Column " + i + " sum: " + sum[i])
.forEach(System.out::println);
//Column 0 sum: 3
//Column 1 sum: 6
//Column 2 sum: 9
//Column 3 sum: 12
//Column 4 sum: 5
See also:
• Adding up all the elements of each column in a 2d array
• How to create all permutations of tuples without mixing them?
How to print a 2d array in java using a single for-loop?
I tried to search answers but only found solutions using multiple loops.
Example array:
[
[1, 2, 3],
[4, 5],
[6, 7, 8],
[9]
]
Example output (the exact format does not matter):
1, 2, 3, 4, 5, 6, 7, 8, 9
With a single for-loop, not a nested loop.
So not something like this:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
}
The principle to read a 2D array with a single loop : one [H,W] 2D matrix could be computed as a 1D matrix of HxW length.
On this basis a solution could be:
int[][] arr = {{1, 2, 3}, {4, 5, 8}, {5, 6, 7}};
int hight = arr.length;
int width = arr[0].length;
for (int i = 0; i < width * hight; i++) {
int li = i / hight;
int col = i % hight;
System.out.print(arr[li][col]);
if (col == width - 1) System.out.println();
}
Output:
123
458
567
If you need to know any algorithm for using only one loop you may try to use some like this:
public static void main(String[] args) {
int[][] arr = {{1, 2}, {3, 4}};
int currSubArrayNum = 0;
for (int i = 0; currSubArrayNum < arr.length; i++) {
System.out.println(arr[currSubArrayNum][i]);
if (i == arr[currSubArrayNum].length - 1) {
currSubArrayNum++;
i = -1;
}
}
}
Output will be next:
1
2
3
4
But if you need some simple solution for use in your program just use Arrays.toString:
public static void main(String[] args) {
int[][] arr = {{1, 2}, {3, 4}};
for (int[] anArr : arr) {
System.out.println(Arrays.toString(anArr));
}
}
With output:
[1, 2]
[3, 4]
You can define the for statement without an increment expression and transfer control of it to the inner if statement as follows:
int[][] arr = {{1, 2, 3}, {4, 5}, {6, 7, 8}, {9}};
for (int i = 0, j = 0; i < arr.length; ) {
if (arr[i] != null && j < arr[i].length) {
System.out.print(arr[i][j] + ", ");
j++;
} else {
j = 0;
i++;
}
}
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9,
Create row and col pointer and update when they reach the edge.
Swift code:
func singleLoopArrayTraversal(_ data: [[Int]]) {
//Time complexity: O(n)
if data.count == 0 {
return
}
var row = 0
var col = 0
while row < data.count {
print("data[\(row)][\(col)] : \(data[row][col])")
if col == data[row].count - 1 {
row += 1
col = -1
}
col += 1
}
}
singleLoopArrayTraversal([[1, 2], [3, 4], [5, 6]])
I am trying to generate 2d random array similar to:
array[random][random2]
{
{1, 2},
{6, 4},
{-1, 5},
{-2}
}
the values in the array are also random, It may have -9 to -1 to 1 to 9 numbers.
Here's what i got:
public class gen2dArray {
public static void main(String args[]) {
Random random = new Random();
int n = 0;
int max = 5, min = 1;
n = random.nextInt(max - min + 1) + min;
int maxRowCol = (int)Math.pow(2,n);
int RandMaxRows = random.nextInt(maxRowCol);
int RandMaxColums = random.nextInt(maxRowCol);
int [][] array = new int [RandMaxRows][RandMaxColums];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < random.nextInt(array[i].length)+1; j++) {
array[i][j] = random.nextInt(9) + 1;
}
}
System.out.println(Arrays.deepToString(array));
}
}
Output 1:
[
[4, 4, 5, 0],
[2, 3, 0, 0]
]
Output 2:
[
[5, 2, 1, 0, 0],
[3, 4, 2, 0, 0],
[3, 1, 5, 0, 0, 0],
[4, 3, 2, 0, 0]
]
There are few problems,
Some outputs are just [[]] or []
2.
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300)
at gen2dArray.main(gen2dArray.java:23)
Getting the zeros in the array. There should be no zeros.
Output one has to be like:
[
[4, 4, 5],
[2, 3]
]
If you do not want to see the zeros, you should avoid making your arrays to big :
int [][] array = new int [RandMaxRows][];
// Code
array[value] = new int[random.nextInt(maxRowCol)];
This method should provide you an array of differents arrays of different sizes and just print out their real inputted values and not the 0 default values.
This is an example of an output :
[
[2, 4, 8, 7, 6, 6, 9],
[1, 3, 4, 2],
[1, 4, 4, 2, 7, 6, 8],
[9, 3, 6, 3, 7, 3],
[4, 5, 3, 2, 5, 2, 8]
]
Here is the modified code :
int [][] array = new int [random.nextInt(maxRowCol)][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[random.nextInt(maxRowCol)];
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(9) + 1;
}
}
When [] is printed, it means your Random did return 0.
A simple way to fix this is to add 1 to the concerned value and maybe decrease the MAX value from one also to keep the logic going.
Here is the code :
int maxRowCol = (int)Math.pow(2,n) - 1;
// Some code
int[][] array = new int [RandMaxRows + 1][];
You can simulate all these scenario by putting a System.out statement just before the array declaration.
System.out.println("RandMaxRows: " + RandMaxRows + "\tRandMaxColums: " + RandMaxColums);
Some outputs are just [[]] or []
This is happening when you are getting RandMaxRows as zero or both row and column are zero. We are using the Random.nextInt(n) for declaring the size of the array. The range of this method is 0 to n-1. So you can fix this by increment the outcome of the method.
n must be positive
This is happening when the RandMaxColums is zero. The input to the random.nextInt(n) must be greater then 0, it throws the exception.
Getting the zeros in the array. There should be no zeros.
The inner for-loop should be like this.
for (int j = 0; j < array[i].length; j++) {
You need iterate the array with it's length, for that any random number generation is not required. Use the current length and fill the array with randomly generated numbers.
Here is the work code for your problem:
public class gen2dArray {
public static void main(String args[]) {
Random random = new Random();
int n = 0;
int max = 5, min = 1;
n = random.nextInt(max - min + 1) + min;
int maxRowCol = (int)Math.pow(2,n);
int RandMaxRows = random.nextInt(maxRowCol);
int RandMaxColums = random.nextInt(maxRowCol);
System.out.println("RandMaxRows: " + RandMaxRows + "\tRandMaxColums: " + RandMaxColums);
int [][] array = new int [RandMaxRows+1][RandMaxColums+1];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int temp = random.nextInt(9);
array[i][j] = temp + 1;
}
}
System.out.println(Arrays.deepToString(array));
}
}
Sample Output:
RandMaxRows: 3 RandMaxColums: 3
[[1, 3, 3, 3], [2, 7, 6, 1], [5, 4, 4, 1], [6, 4, 6, 9]]
public static void swap(int [] array) {
for (int i = 0; i < array.length-1; i++) {
int temp = array[i+1];
array[i+1] = array[i];
array[i]=temp;
}
}
I want to swap each neighboring element by twos. This code gives me [2, 3, 4, 5, 6, 1] instead of [2, 1, 4, 3, 6, 5].
Just increment by 2, since you essentially want to swap every other pair of consecutive elements:
for (int i = 0; i < array.length-1; i += 2) {
^
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So I can just use standard arrays for this, nothing else. I have to find a way to make a method that finds all the cycles in the given permutation and returns them as an array object of arrays. Then I have to place the lowest of each array as the first entry of the array. Then sort them by lowest.
I can't use arraylists or sets or anything.
EDIT: By cycles I mean take the integer value of the initial object and locate the index value that it corresponds to. Take that integer value at that index and do the same. Continue doing this until it points back to an object that's already been referenced.
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
or
This array: [2, 4, 8, 1, 5, 3, 9, 0, 7, 6]
would be these cycles : [2, 8, 7, 0] [4, 5, 3, 1] [9, 6]
and return this : [0, 2, 8, 7], [1, 4, 5, 3], [6, 9]
I am so lost, any help would be wonderful. thanks ahead of time!
Don't ask why I took the time to do this.
EDIT: Totally working now
public class Main {
public Main()
{
}
public static void main(String[] args)
{
int array[] = {0, 4, 2, 8, 7, 9, 1, 6, 5, 3};
Main m = new Main();
int[][] cycles = m.getCycles(array);
for (int i = 0; i < cycles.length; i++)
{
System.out.print("[");
for (int j = 0; j < cycles[i].length; j++)
{
System.out.print(cycles[i][j]);
if (j < cycles[i].length - 1)
System.out.print(", ");
}
System.out.println("]");
}
System.out.println("end debug");
}
public int[][] getCycles(int[] array)
{
int[][] cycles = new int[array.length][array.length];
// initialize the cycles to all -1s, cuz they'll never be in the array
for (int i = 0; i < cycles.length; i++)
{
for (int j = 0; j < cycles[i].length; j++)
{
cycles[i][j] = -1;
}
}
int i = 0;
do {
int nextElement = array[i];
int j = 0;
do {
cycles[i][j] = nextElement;
nextElement = array[nextElement];
j++;
} while (!elementInArray(cycles[i], nextElement) && j < array.length);
i++;
} while (!arrayHasCycled(array, cycles) && i < array.length);
cycles = removeNegativeOnes(cycles, i);
for (i = 0; i < cycles.length; i++)
{
pushForward(cycles[i]);
}
return cycles;
}
public boolean elementInArray(int[] array, int element)
{
for (int i = 0; i < array.length; i++)
{
if( array[i] == element)
return true;
}
return false;
}
public int[][] removeNegativeOnes(int[][] cycles, int numCycles)
{
int [][] newCycles = new int[numCycles][];
for (int i = 0; i < numCycles; i++)
{
int realLenOfCycle = indexOf(-1, cycles[i]);
newCycles[i] = new int[realLenOfCycle];
for (int j = 0; j < newCycles[i].length; j++)
{
newCycles[i][j] = cycles[i][j];
}
}
return newCycles;
}
public int indexOf(int element, int[] array)
{
int index = -1;
for (int i = 0; i < array.length; i++)
{
if (array[i] == element)
return i;
}
return index;
}
public boolean arrayHasCycled(int[] array, int[][] cycles)
{
for (int i = 0; i < array.length; i++)
{
boolean cycleHasValue = false;
for (int j = 0; j < cycles.length; j++)
{
for (int k = 0; k < cycles[j].length; k++)
{
if (cycles[j][k] == array[i])
cycleHasValue = true;
}
}
if (!cycleHasValue)
return false;
}
return true;
}
public void pushForward(int [] array)
{
int lastElement = array[array.length - 1];
for (int i = array.length - 1; i > 0; i--)
{
array[i] = array[i - 1];
}
array[0] = lastElement;
}
}
Output:
[0]
[1, 4, 7, 6]
[2]
[3, 8, 5, 9]
From what I understand, you're asked us to create a code which executes the following algorithm:
Create a one-dimensional array of integers, array
For each element in that array, nextElement do the following:
Create a new one-dimensional array, currCycle that will be added to a two-dimensional array, cycles.
Set the first element of that array to nextElement.
nextElement then becomes array[nextElement]
If nextElement is already in currCycle, continue onto the next element of array
Check if all the elements of array are in cycles, and if so, stop executing this algorithm.
Finally, return the cycles as a two-dimensional array with the index that was being used instead of the element at that index, which is what the current array consists of. To accomplish this, just cyclically (in the normal sense) push each element of the array forward one index.
This doesn't follow your examples exactly, but I think you may have malformed your examples, for instance:
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
The first element 0 is 0, so when you get 0, it's already in the current cycle, so go to the next element, the element at index 1, which is 4. Once you're at 4 go to the fourth element, which is 7 not 8!
0 1 2 3 4
[0, 4, 2, 8, 7...