Union of multiple arrays - java

I am using this code in order to create a certain number of arrays and fill them with certain numbers:
public void CreateVars() {
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for (int j = 0; j < i; j++) {
System.out.println("Enter the number of values: ");
int p = s.nextInt();
System.out.println("Enter the numbers: ");
var[j] = new int[p];
for (int q = 0; q < p; q++) {
int n = s.nextInt();
var[j][q] = n;
}
}
}
How can I use the created arrays and do a union, for ex. A union B union C, since there is always a different number of arrays.
Thanks in advance

change your method to return the created array.
create a second method that takes the 2-dimansional array as parameter and returns a 1-dimensional array. This will to the union as I will show later
use Arrays.toString() to display the arrays content via System.out.println()
in the new method create a variable for the 1-dimensionl target array.
then loop over the first dimension of the parameter:
for(int[] subArray : parameterArray)
in that loop create a new temporary 1-dimensional array variable with the size of the current size of the target variable plus the size of the current subArray.
int[] tempArray = Arrays.copyOf(targetArray,targetArray.length+subArray.length]);
iterate over the subArray and copy the current value at the appropriate position in the temp array.
when finished the inner loop store the tempArray as targetArray
targetArray = tempArray;

Related

How can you show how positions have changed after selection sort?

I coded a selection sort program and I was wondering if I wanted to add-on to it by showing how the positions of the values have changed, if it would be possible?
this is my selection sort code
import java.util.Scanner;
public class SelectionSort {
public static void main(String args[]) {
// int[] arr = {5,4,3,2,1}; // This is my array
int min = 0;
Scanner sc = new Scanner(System.in);
System.out.println("No of elements : ");
int noOfElements = sc.nextInt();
int[] arr = new int[noOfElements];
System.out.println("Give elements : ");
for (int i = 0; i < noOfElements; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < arr.length; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elemenst : " + arr[i]);
}
}
}
If you are trying to get array after each iteration, then you should print at the end of each iteration using Arrays#toString() to print complete array
for (int i = 0; i < arr.length; i++) {
...
.....
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elements : " + Arrays.toString(arr));
}
I don't know if your 'task' is to write your own sort method, but if you are looking for sorting an array you should use this:
public static void main(String[] args) {
int[] arr = {5,4,3,2,1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
Never assume what a User might enter and therefore never assume that the first entry will be the minimum value.
This question has been showing up a lot in StackOverflow and therefore I can only assume this is homework. With this in mind I'm sure the assignment intent is to accept a specific number of random integer values from the User, place those values into a Integer Array, then sort that array in ascending order. While the sorting process is taking place show (display in console) what steps are taking place (which values are swapped within the array).
Here's a tip, research the Bubble Sort and the little bit of code it takes to accomplish the sorting task of Integer numbers within a Integer Array. In general a Bubble Sort utilizes two for loops to carry out a sort. It is within the second for loop where you can detail the process (steps) taken to carry out the sort as towards which Array element values are swapped with other element values as the sort is carried out. It would be within the if statement code block which checks whether or not the previous Array element is greater than the current Array Element.
Good luck.

Find the dimensions of a 2D array in java

I'm playing around with Arrays in Java and had this doubt. How do I find the dimensions of a 2D array in java? For example, I get an array input from System.in and pass it in another method like this:
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
findSize(arr);
/*
*
*Other code
*
*/
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
Both dimensions of the array are greater than 0. Appreciate the help.
This method:
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
is getting as parameter a 2 dimentional array
hence you should do:
findSize(int[][] inputArr){
int heiht = inputArr.length;
int width = inputArr[0].length;
}
I just need to access the 0th element of the array like this:
int size = inputArr[0].length;
This would do the trick!
A 2-dimensional array is an array of arrays. To get the actual length of the second dimension (which can be different for each array entry of the first dimension) do this:
int[] findSize(int[][] inputArr) {
int[] size = new int[inputArr.length];
for (int i = 0; i < inputArr.length; i++) {
size[i] = inputArr[i].length;
}
return size;
}
To get 2D-Array dimension 1:
int size_1 = inputArr.length;
To get 2D-Array dimension 2:
int[] size_2 = findSize(inputArr);

Scalar Multiplication

EDIT
The question is this: Scalar multiplication is defined as B = A * s, where B and A are equally sized matrices (2D array of numbers, in this example let's use integers) and s is a scalar value. Each element of A is multiplied to s, which is then stored in the corresponding element in matrix B.
Write a program that accepts a 4x4 matrix and a scalar value, and perform scalar multiplication, storing the result in a separate 4x4 matrix.
import java.util.*;
public class arrayExercises {
public static void main (String [] args){
//Scalar Value
Scanner sc = new Scanner (System.in);
int scalar = 0;
//Array for A
int matrix [][];
matrix = new int [4][4];
System.out.println("Enter the numbers in the 4x4 matrix");
for (int i=0; i < matrix.length; i++)
{
for (int j =0; j<matrix[i].length; j++)
matrix[i][j] = sc.nextInt();
}
System.out.println("Enter scaler value:");
scalar = sc.nextInt();
sc.close();
}
}
not giving a direct solution. giving you a hint instead.
so far from your code, you have created a matrix and withing 2 for loop you have set the values of the matrix from user input.
now to get a scalar multiplication you need to do a similar operation. create another matrix of the same size as the previous matrix. and in a similar way within 2 loop multiply each and every element of the old matrix with the scalar value and set it to the coresponding index of the new matrix.
System.out.println("Enter scaler value:");
scalar = sc.nextInt();
int scalarMatrix [][];
scalarMatrix = new int [4][4];
for (int i=0; i < scalarMatrix.length; i++)
{
for (int j =0; j<scalarMatrix[i].length; j++)
scalarMatrix[i][j] = (int)(matrix[i][j]*scalar);
}
Something along these lines should work. What you are doing is getting each result from the initial matrix and essentially copying them into the new matrix but multiplying it by the variable "scalar" as you do so.

Random number from an array

I tried to generate a sorted list of random data with no duplicates in descending order for my array. It also returns number of duplicates, but it keeps printing out nothing but zero .... Can anyone help me please :(
// 2. Ask the user for size of arbitrary numbers.
System.out.print("Please enter a size for arbitray numbers: ");
int size = indata.nextInt();
int [] SortedNumbers = new int [size];
// 3. Process arbitrary numbers and remove all duplicates
int numDuplicates = generate_data(SortedNumbers);
// 4. Print the numbers and number of duplicates
printArray(SortedNumbers, numDuplicates);
and here is the random method
public static int generate_data (int [ ] list){
int duplicates = 0;
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
return duplicates;
}
here is the print_array method
public static void printArray(int [] list, int duplicates) {
// Additional code required
System.out.println("\nSize of array: " + list.length + " .Numbers of duplicates: " + duplicates); for (int i = 0; i<list.length; i++){
System.out.printf("%7d", list[i]);
if ((i + 1) % 10 == 0){
System.out.println();
}
}
}
random.nextInt(n.length)
gives you a random index of your array.
But printing the value corresponding to this index, will always give you 0. As you never store any other value in the array.
You should rather do something like this :
int[] list = new int[10];
int duplicates = 0;
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int nextVal = random.nextInt(list.length);
System.out.println("list["+i+"] = "+ nextVal);
// test duplicates
for (int index = 0; index < i; index++) {
if (list[index] == nextVal) {
duplicates++;
break;
}
}
list[i] = nextVal;
}
return duplicates;
Your generate_data method always returns 0, since the local field duplicates is initialized with a 0 value and never changed.
The n field referenced by your generate_data method (which you haven't posted) is likely to be an int[], but its elements might not have been initialized (hence the print out will print default value 0, if within array index).
Hence your numDuplicates local field is always 0 too.
Notes
Your Random initialization is not performing. You should initialize a static Random object in your class and re-use it, instead of re-initializing every time in your generate_data method.
You probably want to have a look at coding conventions for Java in terms of field naming
You might want to post the code in your printArray method as well

How to set the initial value of a multidimensional array in java

2DI need to use a two-dimensional array of doubles to store grades. The first dimension of the array will represents each student while the second dimension represents the grade for each assignment. The maximum number of assignments for any course is provided when the course is created. I need to make it so that grades that have not been assigned are given an initial value of -1
I know that for single arrays you can do this
double[] grade = new double[10];
for (double i = 0; i < size; i++) {
array[i] = -1;
}
How would I do it for a 2D array?
try this
double[][] grade = new double[10][10];
for (double[] e : grade) {
Arrays.fill(e, -1);
}
First all, you can't do this
double[] grade = new int[10];
double[] and int[] are incompatible types.
To declare a 2D array just use two sets of square brackets
double[][] grade = new double[10][10];
This will give you a total of 100 indices, max index being [9][9], and min[0][0].
To iterate through the array you use a nested loop
for (int i = 0; i < grade.length; i++){ // iterates each student
for (int j = 0; j < grade[i].length; j++){ // iterates each grade
// do something with grade[i][j]
}
}

Categories

Resources