array merge function
Answers
Answer:
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//initializing length of each array
int length = 0;
while(length<10) {
System.out.println("Enter an array length (must be 10 or greater):");
length = scan.nextInt();
}
int list1[] = new int [length];
int list2[] = new int [length];
int temp[] = new int [length*2];
//initializes vals of each array with random numbers 1-100
for(int i = 0; i < length; i++) {
list1[i] = (int)(Math.random()*100)+1;
list2[i] = (int)(Math.random()*100)+1;
}
//prints 1st array
System.out.print("\nFirst Array: ");
for(int l = 0; l < length; l++) {
System.out.print(list1[l] + " ");
}
//prints 2nd array
System.out.print("\n\nSecond Array: ");
for(int c = 0; c < length; c++) {
System.out.print(list2[c]+ " ");
}
//checks for duplicates
//removes zeroes and combines arrays in temp
//writes new array with each nonzero value of merged arrays minus duplicates
int e = 0;
for(int k = 0; k < length*2; k+=2) {
//int e = 0;
temp[k] = list1[e];
e++;
}
e = 0;
for(int q = 1; q < length*2; q+=2) {
temp[q] = list2[e];
e++;
}
for(int beg = 0; beg < temp.length-1; beg++) {
for(int end = beg+1; end < temp.length; end++) {
if(temp[end] == temp[beg]) {
temp[end] = 0;
}
}
}
//prints merged array
System.out.print("\n\nMerged Array: ");
for(int w = 0; w < temp.length; w++) {
if(temp[w] != 0) {
System.out.print(temp[w] + " ");
}
}
}
}
Explanation:
This is my code for Edhesive Assignment 6--Merge Arrays written in Java.
Even if this isn't exactly what you are looking for I hope this helps. The requirements for this particular assignment were to initialize two arrays with an inputted amount of random numbers (ranged from 1-100), then to merge them (alternating from the first to second array with each index), and finally to remove any and all duplicates in the merged array and print it to the screen.
Tips!!
- when in doubt, add more variables to help you count iterations, trigger a flag, etc.
- logic through your code as if you are the computer, go line by line and say it to yourself or even write it out
- give variables clear names
- comment your code as you write it!! I know it can be boring but it will help in the long run!!!