I am trying to merge to arrays of int type with the same size. Here's my code
public class classA
{
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
count++;
arr3[count] = arr2[i];
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
public static void main(String[] args) throws IOException
{
int arr1[] = {1,2,3};
int arr2[] = {4,5,6};
int arr3[] = mergeArray(arr1,arr2);
}
}
When I try printing the numbers in first for loop, it gives me 1,4,2,5,3,6 which the correct output. But, When I try printing it outside the first for loop it gives me output 1,2,3,6,0,0. Can someone help me?
TIA
In your for loop, when you copy from arr2 you need to increment your count.
arr3[count] = arr2[i];
count++;
You could also simplify your code a bit like,
static int[] mergeArray(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length * 2];
int count = 0;
for (int i = 0; i < arr1.length; i++) {
arr3[count++] = arr1[i];
arr3[count++] = arr2[i];
}
return arr3;
}
And print in main like
int arr3[] = mergeArray(arr1, arr2);
System.out.println(Arrays.toString(arr3));
or in Java 8+, use a flatMap and IntStream like
static int[] mergeArray(int[] arr1, int[] arr2) {
return IntStream.range(0, arr1.length)
.flatMap(i -> IntStream.of(arr1[i], arr2[i])).toArray();
}
for the same result.
Following your code, you forget to upgrade the count after appending the second value:
public class classA
{
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
count++;
arr3[count] = arr2[i];
count++; //////////////// here!
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
public static void main(String[] args) throws IOException
{
int arr1[] = {1,2,3};
int arr2[] = {4,5,6};
int arr3[] = mergeArray(arr1,arr2);
}
}
explain:
in you code you do count++; just once in the foor loop, but, the foor loop goes from 0 to arr1.length, the is equal to arr3.length/2, it means you forget the half of the values, that's why the 0's appear here, because when you start a new array the defaul value in int[] are 0.
Use arr3[count+1] = arr2[i] and count += 2 instead.
It could be easily understood than using count++ twice.
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
arr3[count+1] = arr2[i]; ///////here
count+=2; ///////and here
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
You simply need to add two values and then increase the kth value.
static int[] array1 = { 1, 2, 3, 4,9 };
static int[] array2 = { 5, 6, 7, 8 };
private static void mergeArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length + arr2.length];
int k = 0;
for (int i = 0,j=0; i < arr1.length && j < arr2.length; i++,j++) {
arr3[k] = arr1[i];
arr3[++k] = arr2[j];
k++;
}
for (int i = 0; i < arr3.length; i++) {
System.out.println("arr3: " + arr3[i]);
}
}
Related
How can I merge two arrays in ascending order?
I have the code below and I need to merge this array in ascending order, and it should be in a separate method. So in this case the method should return {1, 4, 8, 9, 11, 12, 13}
public class MergingArrays {
public static void main(String[] args) {
int [] array1 = {4, 8, 12, 13};
int [] array2 = {1, 9, 11};
merge(array1, array2);
}
public static int[] merge(int array1[], int array2[]) {
}
}
Assuming that you are looking to merge two sorted arrays, you could do it like this.
public static int[] merge(int array1[], int array2[]) {
int i = 0, j = 0, k = 0;
int size1 = array1.length;
int size2 = array2.length;
int[] result = new int[size1 + size2];
while (i < size1 && j < size2) {
if (array1[i] < array2[j]) {
result[k++] = array1[i++];
} else {
result[k++] = array2[j++];
}
}
// Store remaining elements
while (i < size1) {
result[k++] = array1[i++];
}
while (j < size2) {
result[k++] = array2[j++];
}
return result;
}
public static int[] merge(int[] array1, int[] array2) {
int totalElements = array1.length + array2.length, array2Index = 0;
int[] toReturn = new int[totalElements];
for (int i = 0; i < array1.length; i++) {
toReturn[i] = array1[i];
}
for (int i = array1.length; i < totalElements; i++) {
toReturn[i] = array2[array2Index++];
}
//Manual Ascending Array Sorting
for (int i = 0; i < totalElements; i++) {
for (int j = 0; j < totalElements; j++) {
if(toReturn[i] < toReturn[j]) {
int temp = toReturn[i];
toReturn[i] = toReturn[j];
toReturn[j] = temp;
}
}
}
return toReturn;
}
You can use apache commons class and the sort function of Collections class
import org.apache.commons.lang.ArrayUtils;
import java.util.Collections;
public class MergingArrays {
public static void main(String[] args) {
int [] array1 = {4, 8, 12, 13};
int [] array2 = {1, 9, 11};
merge(array1, array2);
}
public static int[] merge(int array1[], int array2[]) {
return Collections.sort(ArrayUtils.addAll(array1, array2));
}
}
I have this professor that wants us to make a using the method header
Public static int[] eliminateDuplicates(int[] arr)
The program uses a randomly generated array to see if there are duplications but the user gives a limit on how many indexes's the random array has. Here is what I have but it's not working.
import java.util.Random;
import java.util.Scanner;
public class Dublicates
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++)
{
a[i] = generator.nextInt(a.length*2);
}
int[] result = eliminateDuplicates(a);
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result)
{
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
{
return result;
}
}
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
As your statements making the final result is inside the for loop, the statements inside for will only run once and will not give the right answer.
So you have to change your code as follows.
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
return result;
}
The default values in the integer array is 0, The Random.nextInt() can generate 0 random value, When you run linear search then 0 will not be included in the final resultant array.
I have modify Random.nextInt() so that it will not generate 0 random number:
import java.util.Random;
import java.util.Scanner;
public class HelloCodiva
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++){
a[i] = generator.nextInt(a.length*2)+1;//So that 0 is not generated
}
int[] result = eliminateDuplicates(a);
for (int originalValue: a){
System.out.println(originalValue+ " ");
}
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result){
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
System.arraycopy(temp, 0, result, 0, size);
return result;
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
I was told to make
void mergeArrays(int[] ar1 , int[] ar2)
For an input like this:
int[] ar1 = {1,2,3,4}
int[] ar2 = {5,6,7,8}
This is my code :
public static void mergeArray(int[] ar1 , int[] ar2) {
int[] res = new int[ar1.length+ar2.length];
int counter = 0;
for(int a = 0; a<ar1.length; a++)
{
res[a] = ar1[a];
counter++;
}
for(int b = 0; b<ar2.length; b++)
{
res[counter++] = ar2[b];
}
for(int temp = 0; temp<res.length;temp++)
{
System.out.print(res[temp]+" ");
}
Output 12345678.
This is done using 2 loops. Now, how can I do it using a single loop?
Yes, you can do it in one loop,
int len = arr1.length + arr2.length;
int[] res = new int[len];
for(int i=0, j=0; i<len; i++) {
if(i<arr1.length){
res[i] = arr1[i];
}else{
res[i] = arr2[j];
j++;
}
}
This will work also, when both arrays are of different length.
Different length arrays
int[] result = new int[ar1.length + ar2.length];
for(int i = 0; i < result.length; i++) {
result[i] = i < ar1.length ? ar1[i] : ar2[i - ar1.length]; // comparison
}
Equal length arrays
int[] result = new int[ar1.length + ar2.length];
for(int i = 0; i < ar1.length; i++) {
result[i] = ar1[i]; // no
result[ar1.length + i] = ar2[i]; // comparison
}
See (and execute) the full implementation here.
Is there a way to use the first function in the second one to create a double array with random numbers?
public static int[] build1(int size) {
int[] arr = new int[size];
for (int i=0 ; i < arr.length ; i++)
arr[i] = (int)(Math.random() * 127);
return arr;
}
public static int[][] build2(int row, int col) {
int[][] arr2 = new int[row][col];
for (int i = 0; i < arr2.length; i++) {
for (int j = 0; j < arr2[i].length; j++) {
arr2[i][j] = (int)(Math.random() * 127);
}
}
return arr2;
}
I would assume the following should work.
public static int[][] build2(int row, int col) {
int[][] arr2 = new int[row][col];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = build1(col);
}
return arr2;
}
Okay, I know this question doesn't show research effort, but I've been going through this code so many times and I couldn't figure out was I was doing wrong. I know there are many Mergesort implementation examples but I wanted to do it my way. Any help is appreciated, thanks.
import java.util.Scanner;
public class MergeSort
{
public static int[] mergeSort(int[] arr)
{
if (arr.length > 1)
{
int[] arr1 = splitLeft(arr);
int[] arr2 = splitRight(arr);
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
return merge(arr1, arr2);
}
else
return arr;
}
public static int[] splitLeft(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[middle];
for (int i = 0; i < middle; i++)
newarr[i] = arr[i];
return newarr;
}
public static int[] splitRight(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[arr.length - middle];
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
return newarr;
}
public static int[] merge(int[] arr1, int[] arr2)
{
int[] sorted = new int[arr1.length+arr2.length];
int i1 = 0;
int i2 = 0;
int i = 0;
while (i1 < arr1.length && i2 < arr2.length)
{
if (arr1[i1] < arr2[i2])
{
sorted[i] = arr1[i1];
i1++;
}
else
{
sorted[i] = arr2[i2];
i2++;
}
i++;
}
while (i1 < arr1.length)
{
sorted[i] = arr1[i1];
i1++;
i++;
}
while (i2 < arr2.length)
{
sorted[i] = arr1[i2];
i2++;
i++;
}
return sorted;
}
public static int getNum(int x)
{
int num = (int)(Math.random()*x + 1);
return num;
}
public static void printArr(int[] arr)
{
System.out.println();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
static Scanner reader = new Scanner(System.in);
public static void main(String [ ] args)
{
int i;
System.out.println("Type the length of the array");
int n = reader.nextInt();
System.out.println("Type the range of the random numbers generator");
int range = reader.nextInt();
int[]arr = new int[n];
for (i = 0; i < n; i++)
arr[i] = getNum(range);
printArr(arr);
int[] sorted = new int[n];
sorted = mergeSort(arr);
printArr(sorted);
}
}
I think the problem is in your splitRight function. Consider this code:
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
This tries to copy the ith element from arr to the ith position of newarr, but this is incorrect. For example, if the array arr has ten elements, you want to copy element 5 of arr to position 0 of newArr, element 6 of arr to position 1 of newarr, etc.
To fix this, consider trying something like this:
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
Hope this helps!
When you do
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
You are surely asking for positions in the original array and at the same time looking for them in the new array (which happens to be shorter).