Generate a random 2d array with random row length - java

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]]

Related

Sort selected column from array

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]

Why is my selection sort program not giving the correct output for the last few numbers?

I've been going through this MOOC.fi Java course and got to the problem about developing a selection sort algorithm on this page (https://java-programming.mooc.fi/part-7/2-algorithms). I don't have the solutions, so I was wondering if anyone here could help me solve this problem. Basically, I got through all the steps uptil Part 4, but when I tried to make the selection sort method, my method only sorted the numbers correctly until it got to the second to last number, and then it started switching the numbers incorrectly. Can anyone look over my code and tell me where I went wrong?
import java.util.Arrays;
public class MainProgram {
public static void main(String[] args) {
// Testing methods
// Test Part 1
int[] numbers = {6, 5, 8, 7, 11};
System.out.println("Smallest: " + MainProgram.smallest(numbers));
// Testing Part 2
System.out.println("Index of the smallest number: " + MainProgram.indexOfSmallest(numbers));
// Testing Part 3
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 0));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 1));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 2));
// Testing Part 4
int[] numbers2 = {3, 2, 5, 4, 8};
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 1, 0);
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 0, 3);
System.out.println(Arrays.toString(numbers2));
// Testing Part 5
int[] numbers3 = {8, 3, 7, 9, 1, 2, 4};
MainProgram.sort(numbers3);
}
// Part 1
public static int smallest(int[] array) {
int smallest = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
return smallest;
}
// Part 2
public static int indexOfSmallest(int[] array){
int smallest = array[0];
int i;
int finalIndex = 0;
for (i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 3
public static int indexOfSmallestFrom(int[] table, int startIndex) {
int smallest = table[startIndex];
int i = startIndex;
int finalIndex = 0;
for (i = startIndex; i < table.length; i++) {
if (table[i] < smallest) {
smallest = table[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 4
public static void swap(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Part 5
public static void sort(int[] array) {
int smallestIndex;
for (int i = 0; i < array.length; i++) {
smallestIndex = indexOfSmallestFrom(array, i);
swap(array, smallestIndex, i);
System.out.println(Arrays.toString(array));
}
}
}
Here is the wrong output:
[1, 3, 7, 9, 8, 2, 4]
[1, 2, 7, 9, 8, 3, 4]
[1, 2, 3, 9, 8, 7, 4]
[1, 2, 3, 4, 8, 7, 9]
[1, 2, 3, 4, 7, 8, 9]
[8, 2, 3, 4, 7, 1, 9]
[9, 2, 3, 4, 7, 1, 8]
In the 3 block you set the
finalIndex = 0;
It should be set to the startIndex

Print 2D array with a single for loop

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]])

Swap neighboring elements grouped by two's [1,2,3,4,5,6] = [2,1,4,3,6,5]

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) {
^

Using an array of arrays (int[][]), create a method to find all cycles within a given permutation [closed]

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...

Categories

Resources