Java- Moving elements from a ArrayList to an Array - java

I currently have a randomly mixed ArrayList.
public static void main(String[] args) {
ArrayList<Integer> solution = new ArrayList<>();
for (int i = 1; i <= 48; i++) {
solution.add(i);
}
Collections.shuffle(solution);
This gives me a ArrayList with the numbers 1-48 randomly mixed. Now I have 4 arrays and I want to randomly add the elements of the ArrayList with out repetition.
int[] heartsRow = new int[14];
int[] diamondsRow = new int[14];
int[] spadesRow = new int[14];
int[] clubsRow = new int[14];
The reason the new arrays contain 14 elements is because the first two elements will always be the same.
heartsRow[0] = 1;
heartsRow[1] = 0;
diamondsRow[0] = 14;
diamondsRow[1] = 0;
spadesRow[0] = 27;
spadesRow[1] =0;
clubsRow[0] = 40;
clubsRow[1] = 0;
I want to completely fill each array with non-repeating elements of the ArrayList.

You can make 4 for loops, from 0 to 11, 12 to 23, 24 to 35 and 36 to 47, and add in your lists.
for (int i = 0; i < 12; i++)
heartsRow[i + 2] = solution.get(i);
for (int i = 0; i < 12; i++)
diamondsRow[i + 2] = solution.get(i + 12);
for (int i = 0; i < 12; i++)
spadesRow[i + 2] = solution.get(i + 24);
for (int i = 0; i < 12; i++)
clubsRow[i + 2] = solution.get(i + 36);

You could use a counting loop over the list,
increment the counter by 4 in each step,
and assign elements to the arrays with adjusted offsets:
for (int i = 0; i + 3 < solution.size(); i += 4) {
int j = i / 4;
heartsRow[2 + j] = solution.get(i);
diamondsRow[2 + j] = solution.get(i + 1);
spadesRow[2 + j] = solution.get(i + 2);
clubsRow[2 + j] = solution.get(i + 3);
}

Related

Sort 2D array by average value of each line

I have complex task to differently sort two dimensional array manually.
So far I get done those tasks:
User needs to input row size from 10 - 20,
Generate 2D array where row size is user input and column size is randomly generated from 10-50,
Each array is filled with randomly generated numbers from 100 - 999,
Output each array row by its descending value,
Output average value of each array line,
Output on screen array with biggest average value,
So far I can't solve task Nr. 7. Output sorted two dimensional array by each lines average value.
Tried to implement new arrayAverage in loop to sort lines it didn't work.
Array just need to be sorted without creating new array.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
int array2ndDsize = new Random().nextInt(40) + 10;
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you entered is too big or too small!!!");
} else {
//initializing array
int[][] array = new int[array1stDsize][array2ndDsize];
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
System.out.println();
System.out.println("New array from average values: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Most valuest array is: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
System.out.print("Its founded " + row + ". row and it's value is: ");
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
System.out.println();
System.out.println();
//2D array sorting by average values
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}
The part of your code that calculates the average:
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
is slightly wrong, you need to set the average variable to zero before calculating the average of the next rows:
...
arrayAverage[i] = average;
average = 0;
With the Java Streams one can get the matrix sorted by average of rows pretty elegantly, namely:
Arrays.sort(array, comparingDouble(row -> IntStream.of(row)
.average()
.getAsDouble()));
To sort the array one uses the method Arrays.sort, and then for each row one gets its average as a double value IntStream.of(row).average().getAsDouble(), and used as the sorting parameter comparingDouble(....).
A running example:
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static java.util.Comparator.comparingDouble;
public class Test {
public static void main(String[] args) {
int array[][] = {{10, 20, 30},{40, 50, 60}, {1,2,3} };
Arrays.sort(array, comparingDouble(row -> IntStream.of(row).average().getAsDouble()));
Arrays.stream(array).map(Arrays::toString).forEach(System.out::println);
}
}
The output:
[1, 2, 3]
[10, 20, 30]
[40, 50, 60]
For the reverse order use instead:
Arrays.sort(array, comparing(row -> IntStream.of(row).average().getAsDouble(), reverseOrder()));
The output:
[40, 50, 60]
[10, 20, 30]
[1, 2, 3]
EDIT: WITH NO STREAMS
Without using streams what you can do is the following:
1 - Get the array with the averages of the matrix rows:
float[] arrayAverage = average(matrix);
You already know how to calculate the average, therefore you just need to extract a method out of the code that you have created, namely:
private static float[]average(int[][] array) {
float[] arrayAverage = new float[array.length];
float sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
arrayAverage[i] = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
sum = 0;
}
return arrayAverage;
}
2 - Create an array that will represent the rows and initialized as the following:
int [] row_position = new int [arrayAverage.length];
for(int i = 0; i < row_position.length; i++)
row_position[i] = i;
3 - Sort the arrayAverage using the easiest sort, the bubble sort. While sorting that array update accordingly the positions stored on the row_position:
for(int i=0; i < arrayAverage.length; i++){
for(int j=1; j < (arrayAverage.length-i); j++){
if(arrayAverage[j-1] > arrayAverage[j]){
float temp = arrayAverage[j-1];
arrayAverage[j-1] = arrayAverage[j];
arrayAverage[j] = temp;
int temp_pos = row_position[j-1];
row_position[j-1] = row_position[j];
row_position[j] = temp_pos;
}
}
}
4 - Now that you have the row_positions array that tells you how the sorted rows should be rearranged, you just need to swap the rows accordingly:
int[][] tmp_matrix = new int [matrix.lenght][];
for (int i = 0; i < tmp_matrix.length; i++) {
tmp_matrix[i] = matrix[row_position[i]];
}
matrix = new_matrix;
Bear in mind, however, that for simplicity-sake I have assumed a quadratic matrix of NxN, and the above solution can be improved performance-wise.
At last, made it to work, looks like this.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you enteraed is too big or too small!!!");
} else {
int[][] array = new int[array1stDsize][];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = new int[random.nextInt(31) + 10];
for (int j = 0; j < array[i].length; j++) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
for (int i = 0; i < array.length; i = i + 1) {
float sum = 0;
for (int j = 0; j < array[i].length; j = j + 1) {
sum = sum + array[i][j];
}
float average = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
// array lines sorting from by average value increasing
for (int i = 0; i < arrayAverage.length; i = i + 1) {
for (int j = i; j > 0; j--) {
if (arrayAverage[j] < arrayAverage[j - 1]) {
float tmpor = arrayAverage[j];
arrayAverage[j] = arrayAverage[j - 1];
arrayAverage[j - 1] = tmpor;
int[] tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
}
System.out.println();
System.out.print("Array from average values sorted: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Incerasing Array line output: ");
arrayOutput(array);
System.out.println();
System.out.print("Most valuest array is array: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}
Output sorted 2d array in ascending order:
int[][] arr = {
{12, 54, 87}, // avg 51
{98, 56, 32}, // avg 62
{19, 73, 46}}; // avg 46
Arrays.stream(arr)
// sort an array by the
// average value of the row
.sorted(Comparator.comparingDouble(row ->
// get the average value or 0 if the row is empty {}
Arrays.stream(row).average().orElse(0)))
// string representation
// of the row content
.map(Arrays::toString)
// output line by line
.forEach(System.out::println);
Output:
[19, 73, 46]
[12, 54, 87]
[98, 56, 32]

In java Most simple way to add non duplicate random numbers to 2D Array

I'm trying to figure out whats the most simple way to add to fill this 2D Array with only non duplicate numbers.
I've tried to use a method with boolean to check the value before adding it, if it already exists but I couldn't make it work.
int[][] x = new int[R][C];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
double z = (Math.random() * ((30 * (j + 1)) - ((30 * j) + 1)) + 1 + ((30 * j) + 1));
card[i][j] = (int) z;
}
}
The best way i will say is to use Set data structure
int row = 2;
int col = 2;
Set<Set<Integer>> rowSet = new HashSet<>();
for (int i = 0; rowSet.size() < row; i++) {
Set<Integer> colSet = new HashSet<>();
for (int j = 0; colSet.size() < col; j++) {
double x = (Math.random() * ((15 * (j + 1)) - ((15 * j) + 1)) + 1 + ((15 * j) + 1));
colSet.add((int) x);
}
rowSet.add(colSet);
}
And finally convert them to array
int[][] arr = set.stream()
.map(i->i.stream()
.mapToInt(Integer::intValue)
.toArray())
.toArray(int[][]::new);
You definitely want to use Random.nextInt() to get a uniform distribution of your int. Most likely you want a Set to track which numbers were already generated.
int[][] cards = new int[ROW][COL];
Random r = new Random();
Set<Integer> generated = new HashSet<>();
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
int n;
do {
n = r.nextInt();
} while (generated.contains(n));
generated.add(n);
cards[i][j] = n;
}
}

Exchange values of two arrays, make another array without repeats and sort from highest to lowest

I know I have to do it with a while or do while loop, but I can't get it working. I also tried with a for loop, but it always gives me an error because I don't know the exact length of the vectors because they are random.
int a = (int)(Math.random() * 3 + 1);
int b = (int)(Math.random() * 3 + 1);
int c = a + b;
int[] arrA = new int[a];
int[] arrB = new int[b];
int[] arrC = new int[c];
for (int i = 0; i < a; i ++) {
arrA[i] = (int)(Math.random() * 10 + 1);
for (int j = 0; j < b; j ++) {
arrB[j] = (int)(Math.random() * 10 + 1);
}
}
Arrays.sort(arrA);
Arrays.sort(arrB);
System.out.println(Arrays.toString(arrA));
System.out.println(Arrays.toString(arrB));
System.out.println(Arrays.toString(arrC));
Take values from arrays arrA and arrB, and insert to arrC
int index = arrA.length;
for (int i = 0; i < arrA.length; i++) {
arrC[i] = arrA[i];
}
for (int i = 0; i < arrB.length; i++) {
arrC[i + index] = arrB[i];
}
Sort arrC
Arrays.sort(arrC);
Reverse the order and store in arrD
for(int l = 0; l < arrC.length; l++) {
arrD[l] = arrC[arrC.length - (l+1)];
}
Remove duplicate (simplified)
Set<Integer> remove=new LinkedHashSet<Integer>();
for(int i = 0;i < arrD.length;i++){
remove.add(arrD[i]);
}
Remove duplicate (usual)
int index2 = 0;
for (int i = 0; i < arrD.length; i++) {
for (int k = 0; k < arrD.length; k++) {
if (arrD[i] != arrD[k]) {
arrE[index2] = arrD[i];
index2++;
}
}
}

Extract array elements to separate array

I have to make a program that extract every 3th element from array. So far i have made the basic array, but im stuck at extracting every 3th element into separate array. How can i do that?
public static void main(String[] args) {
int min = -100;
int max = 100;
int[] array = new int[201];
for( int i = 0; i < array.length; i++) {
array[i] = min + (int)(Math.random()*((max - min) + 1));
To fill in a new array (named array2) with every 3rd item from your array:
int[] array2 = new int[array.length / 3];
int k = 2;
for(int j = 0; j < array2.length; j++) {
array2[j] = array[k];
k += 3;
}
just make your for loop jump by three:
int[] newArray = new int[array.length / 3];
for (int i = 2 ; i < array.length ; i+=3) {
newArray[i/3] = array[i];
}

Int[] to Matrix Java

How do I convert a int[] to a matrix?
Let's say I want to make 6x6 matrix and I have an int[] array with 36 elements.
So the 00 entry is the 0th element of the array, 01: 1 element, 02:, 2nd element and so forth.
how about:
int[] ints = new int[36];
// fill with values
int[][] matrix = new int[6][6];
for (int i = 0; i < ints.length; i++) {
matrix[i / 6][i % 6] = ints[i];
}
To help you understand why this works, add the following inside the loop:
System.out.println("i = " + i + "; i / 6 = " + (i / 6) + "; i % 6 = " + (i % 6) + ";");
for(int i = 0; i < 6; i++)
for(int j = 0; j < 6; j++)
matrix[i][j] = vector[i * 6 + j];

Categories

Resources