How can I merge 2 arrays in 1 loop? - java

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.

Related

Merging two arrays and short that merged array

I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}

How to flatten a 2-dimensional array into a 1-dimensional array

How would i transfer a 2d array into a 1d array in java. I have the code for the 2d array but dont know where to start.
The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80.
public class move
{
public static void main (String[] args)
{
int[][] twoarray = new int[8][10];
int i ;
int j ;
for(i =0; i < 8; i++)
{
for(j = 0; j < 10; j++)
twoarray[i][j] = (i * 10 + j+1);
}
for(i = 0; i < 8; i++)
{
for(j = 0; j < 10; j++)
{
System.out.print(twoarray[i][j]);
System.out.print(" ");
}
System.out.println();
}
int[] array = new int[80];
}
}
Using Java 8
int[] array = Stream.of(twoarray)
.flatMapToInt(IntStream::of)
.toArray();
Using Java 7 or older
int[] array = new int[80];
int index = 0;
for (int[] row : twoarray) {
for (int val : row)
array[index++] = val;
}
You can do in your for loop:
int[] array = new int[80];
int k=0;
for(i = 0; i < 8; i++){
for(j = 0; j < 10; j++){
array[k++]=twoarray[i][j];
}
}

null pointer exception sorting merged array list

I have been trying to figure out how to properly print the return of my method.
When the program prints the return of my method, I am giving a nullPointerException error on line 45(the line where i am trying to print the method).
*I did try to make the return to the method static so it is accessible.
How do I initialize the "answer" variable so that i can print it outside of my method?
Thank you in advance
import javax.swing.JOptionPane;
public class ListSortMerge {
static int[]answer;
public static void main(String[] args) {
int v1 = 0, v2 = 0;
for(int c = 0; c <= 1; c++) {
String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
if (c==0) {
v1 = Integer.parseInt(values);
}
else{
v2 = Integer.parseInt(values);
}
}
int[] numbers1 = new int[v1];
int[] numbers2 = new int[v2];
merge(numbers1,numbers2);
int i;
System.out.println("\nList 1 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v1); i++) {
System.out.println(numbers1[i]);
}
System.out.println("\nList 2 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v2); i++) {
System.out.println(numbers2[i]);
}
System.out.println("\nList after the sort");
System.out.println("--------------------");
for(i = 0; i < (v1+v2); i++) {
System.out.println(answer[i]);
}
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
for(int c = 0; c < (a.length); c++)
{
String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
a[c] = Integer.parseInt(aVal1);
}
for ( int c = 0; c < (b.length); c++){
String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
b[c] = Integer.parseInt(aVal2);
}
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
You have two different answer variables: one is a local variable in the merge function and another is a static field in the class. You never initialize the second one.

How can I split a integer array to n integer array dynamically?

Here I have integer array contains 81 values so that I need to store 9 values per array total I need to get 9 arrays. Eg: array1 from 1 to 9 and array2 from 10 to 18 and array3 from 19 to 27 like that. Can anybody help me how to get this values?
public class demo {
public static void main(String[] args) {
int num = 81;
int numArray = num / 9;
int[] input = new int[num];
for (int i = 0; i < num; i++) {
input[i] = i + 1;
}
for (int j = 0; j < input.length; j++) {
System.out.println(input[j]);
}
}
}
How to get desired result?
You can use System#arraycopy():
int[] first_part = new int[27];
int[] second_part = new int[27];
int[] third_part = new int[27];
System.arraycopy(input, 0, first_part, 0, 27);
System.arraycopy(input, 27, second_part, 0, 27);
...
I've just noticed that you want 9 parts, you can easily put this in a loop and use arraycopy.
public static void main(String[] args) {
int num = 85;
int limit = 5;
int index = 0;
int extra = 0;
int finalArrayIndex = 0;
int[] innerArray = null;
int[] input = new int[num];
boolean isEnd = false;
if (num % limit > 0) {
extra = 1;
}
int[][] finalArray = new int[(num / limit) + extra][limit];
for (int i = 0; i < input.length; i = i + (limit)) {
innerArray = new int[limit];
for (int j = 0; j < limit; j++) {
innerArray[j] = input[index++];
if (index >= input.length) {
isEnd = true;
break;
}
}
finalArray[finalArrayIndex++] = innerArray;
if (isEnd) {
break;
}
}
// just for test
for (int k = 0; k < finalArray.length; k++) {
for (int l = 0; l < finalArray[k].length; l++) {
System.out.println("finalArray[" + k + "]" + "[" + l + "] : "
+ finalArray[k][l]);
}
}
}
This is dynamic solution, you can change value of num and limit variables. I hope this will help you :)
Java Fiddle link : http://ideone.com/jI8IOb
My suggestion is use subList
You can follow these steps.
Store all 81 values in a List (ArrayList)
Then create 9 sub List from that using subList()
You can convert List to array.
List<Integer> fullList=new ArrayList<>();
List<Integer> list1=fullList.subList(0,8); // first 9 elements
Integer[] bar = list1.toArray(new Integer[list1.size()]);

Deleting elements from multi Dimensional Array

I have a 2-dimensional array in java.
For example,
double count=0;
double[][] arr1 =new double[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
arr1[i][j]=count;
count++;
}
}
Now, I want to remove all elements where i or j value was 1.
arr1[1][0], arr1[1][1], arr1[1][2], arr[0][1], arr[2][1] ...
How can I achieve this?
Copies into arr2.
If you had
[1][2][3]
[4][5][6]
[7][8][9]
You'd get
[1][3]
[7][9]
If you wanted
[1][-][3]
[-][-][-]
[7][-][9]
See shijima's answer
double[][] arr2 = new double[arr1.length][arr1[0].length];
int ti = 0, tj = 0;
for(int i=0; i<arr1.length - 1; i++) {
if (i > 0)
ti = i+1;
else
ti = i;
for(int j=0; j<arr1[0].length - 1; j++) {
if (j > 0)
tj = j+1;
else
tj = j;
arr2[i][j] = arr1[ti][tj];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==1 || j==1){
arr1[i][j]=0;
}
}
}
or with much better efficiency :
for(int i=0;i<3;i++){
arr1[i][1]=0;
}
for(int i=0;i<3;i++){
arr1[1][i]=0;
}
ArrayList would make your life a lot easier since you could just call remove(int), but if you insist on arrays you could do this.
double[] tmp = arr1[0];
arr1 = Arrays.copyOfRange(arr1, 1, arr1.length);
arr1[0] = tmp;
You could just avoid adding anything if i = 1, that way you don't need to worry about removing anything, since it will be empty later anyway...
double count = 0;
double[][] arr1 = new double[3][3];
outerLoop: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1) {
continue outerLoop;
}
arr1[i][j] = count;
count++;
}
}
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
System.out.println("arr1[" + x + "][" + y + "]=" + arr1[x][y]);
}
}

Categories