JAVA array concatenation from two different arrays - java

How to concatenate each and every number from 2 arrays and then give the output individually of the new no. formed?
Example:
arr1[1,2,3]
arr2[2,3,5]
output: [12,13,15,22,23,25,32,33,33,35]

Here's another way of doing it that doesn't involve using String.
public static void main(String[] args)
{
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 2, 3, 5 };
int[] arr = concat(arr1, arr2);
System.out.println(Arrays.toString(arr));
}
static int[] concat(int[] arr1, int[] arr2)
{
int i = 0;
int[] arr = new int[arr1.length * arr2.length];
for (int n2 : arr2)
{
int pow10 = (int) Math.pow(10, nDigits(n2));
for (int n1 : arr1)
{
arr[i++] = n1 * pow10 + n2;
}
}
return arr;
}
static int nDigits(int n)
{
return (n == 0) ? 1 : 1 + (int) Math.log10(n);
}
Output:
[12, 22, 32, 13, 23, 33, 15, 25, 35]

Use a for loop inside of a for loop. Then concatenate the item from arr and the item from arr2. I used an ArrayList but you could use a normal array if you know the resultant length of the array.
String[] arr = new String[]{"1", "2", "3"};
String[] arr2 = new String[]{"2", "3", "5"};
List<String> res = new ArrayList<>();
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr2.length; j++) {
res.add(arr[i] + arr2[j]);
}
}
System.out.println(res.toString());
The result is:
[12, 13, 15, 22, 23, 25, 32, 33, 35]

If you just want to display the contents of the two array in the form you have given above you can always try doing this instead of concatinating it.
public class ArrayQuestion {
public static void main(String[] args) {
int arr1[] = {1,2,3};
int arr2[] = {2,3,5};
for(int i=0;i<arr1.length;i++) {
for(int j=0;j<arr2.length;j++) {
System.out.print(arr1[i]);
System.out.print(arr2[j]);
System.out.println();
}
}
}
}
Output :
12
13
15
22
23
25
32
33
35

Related

Print only the numbers, which have been changed

I got curious about a Merge-sorting code.
Description:
This code creates two auxillary arrays left and right and store alternate array elements in them and then copying all elements of left and right subarrays back to original array and printing them. So instead of printing back to the original array, how would it be possible to only print the moved numbers?
class Project {
static void join(int arr[], int left[], int right[],int l, int m, int r){
int i;
for (i = 0; i <= m - l; i++)
arr[i] = left[i];
for (int j = 0; j < r - m; j++)
arr[i + j] = right[j];
}
static void split(int arr[], int left[], int right[],int l, int m, int r) {
for (int i = 0; i <= m - l; i++)
left[i] = arr[i * 2];
for (int i = 0; i < r - m; i++)
right[i] = arr[i * 2 + 1];
}
static void generateWorstCase(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
int[] left = new int[m - l + 1];
int[] right = new int[r - m];
split(arr, left, right, l, m, r);
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
join(arr, left, right, l, m, r);
}
}
public static void main (String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
System.out.println("\nInput array that will result in worst case of merge sort is: \n");
System.out.println(Arrays.toString(arr));
}
}
Here's the output:
System.out.println(Arrays.toString(arr));
My question is..
I would ask, can you, based on the code, only have the output as, like the numbers being moved, and not the entire array?
Example:
The input is:
{ 10 20 30 40 50 }
The output is:
{ 10 50 30 20 40 }
My Desired Output:
{ 50 20 40 }
(The number of inputs varies according to the number of output)..
How would this happen?
Do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (map.get(arr[i]) != i) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
Another solution:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
[Update]
You have requested to change the format of the output so that the numbers are not bounded by []. Note that this is how Arrays.toString or List::toString returns the string. If you do not want an array or a List, you can do it simply as:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
StringBuilder s = new StringBuilder();
int i;
for (i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
s.append(arr[i]).append(", ");
}
}
String output = s.substring(0, s.lastIndexOf(","));
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + output);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
If you want to change the format of the output while keeping the List, you can do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n"
+ list.toString().replace("[", "").replace("]", ""));
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
Iterate over both arrays simultaneously. If input[i] is not equal to output[i] then it has been moved.
List<Integer> moved = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
if (input[i] != output[i]) {
moved.add(input[i]);
}
}

How to print common elements in 2 arrays without sorted output in Java

Given two arrays, find the common elements in them.
Example: [1,45,33,23,22,45,233,21], [5,23,45,0,9,23,1,9] => Output: [1,45, 23]
import java.io.*;
import java.util.*;
class Mycode {
public static void main(String args[]) {
int a[] = {1, 45, 33, 23, 22, 45, 233, 21};
int b[] = {5, 23, 45, 0, 9, 45, 1, 9};
Mycode test = new Mycode();
test.testNumber(a, b);
}
void testNumber(int c[], int d[]) {
System.out.println(Arrays.toString(c));
System.out.println(Arrays.toString(d));
Set<Integer> hset = new HashSet<Integer>();
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
System.out.println(c[i]);
hset.add(c[i]);
}
}
}
System.out.println(hset);
}
}
Actual Output: [1, 45, 33, 23, 22, 4, 233, 21] [5, 23, 45, 0, 9, 5, 1, 9] =>
[1, 23, 45]
HashSet makes no guarantees of the preservation of the insertion order as indicated in the JavaDoc:
It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant
over time.
So I would prefer using a LinkedHashSet. This Set implementation guarantees the preservation of the insertion order. From the JavaDocs:
This linked list defines the iteration ordering, which is the order in
which elements were inserted into the set (insertion-order)
void testNumber(int c[], int d[]) {
System.out.println(Arrays.toString(c));
System.out.println(Arrays.toString(d));
Set<Integer> hset = new LinkedHashSet<>();
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
hset.add(c[i]);
}
}
}
System.out.println(hset);
}
Output:
[1, 45, 23]
You can use a
HashMap
Loop through the first array and add each element with the value false.
Loop through the second and if it's in the hashMap then it's common.
What about something like below? This will be more neat since you don't need to have two for loops, and you don't need to sort it before hand.
public class Mycode {
public static void main(String args[]) {
Integer a[] = {1, 45, 33, 23, 22, 45, 233, 21};
Integer b[] = {5, 23, 45, 0, 9, 45, 1, 9};
Mycode test = new Mycode();
System.out.println(test.testNumber(a, b));
}
public <T> Set<T> testNumber(T [] arra1, T [] arr2){
Set<T> set1 = new HashSet<T>();
Set<T> interset = new HashSet<T>();
Collections.addAll(set1, arra1);
for(T t: arr2){
if(set1.contains(t))
interset.add(t);
}
return interset;
}
}
List<Integer> list = new ArrayList<>(Arrays.asList(array1));
list.retainAll(Arrays.asList(array2));
System.out.println(list);
Solution with time complexity of order N
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n1 = scn.nextInt();
int[] arr1 = new int[n1];
for (int i = 0; i < n1; i++) {
arr1[i] = scn.nextInt();
}
int n2 = scn.nextInt();
int[] arr2 = new int[n2];
for (int i = 0; i < n2; i++) {
arr2[i] = scn.nextInt();
}
HashMap < Integer, Integer > freqMap1 = new HashMap < > ();
for (int i = 0; i < n1; i++) {
int ch = arr1[i];
if (freqMap1.containsKey(ch)) {
int f = freqMap1.get(ch);
freqMap1.put(ch, f + 1);
} else {
freqMap1.put(ch, 1);
}
}
for (int i = 0; i < n2; i++) {
int ch = arr2[i];
if (freqMap1.containsKey(ch)) {
System.out.println(ch);
freqMap1.remove(ch);
}
}
}
}

ArrayList of arrays get index

I have an ArrayList of arrays and i want to change the value of 5
List<int[]> list = new ArrayList<int[]>();
int[] arr1 = {2,4,6};
int[] arr2 = {1,3,5};
list.add(arr1);
list.add(arr2);
for (int[] ss : list)
{
for(int sd : ss)
{
//System.out.println(sd);
if(sd == 5)
{
System.out.println("Yes");
//change 5 to 12
//list.set(list.indexOf(5), 12);
}
}
System.out.println(Arrays.toString(ss));
}
[2, 4, 6] [1, 3, 5]
I want to change 5 to 12
Change your code to :
public static void main(String args[]) {
List<int[]> list = new ArrayList<int[]>();
int[] arr1 = { 2, 4, 6 };
int[] arr2 = { 1, 3, 5 };
list.add(arr1);
list.add(arr2);
for (int[] ss : list) {
for (int i = 0; i < ss.length; i++) {
// System.out.println(sd);
if (ss[i] == 5) { // if current value is 5
System.out.println("Yes");
ss[i] = 12; // set it to 12
}
}
System.out.println(Arrays.toString(ss));
}
}

Java sort 4 arrays into 1 array

I need to efficiently sort through 4 arrays and return 2 results.
The first result will contain all numbers that exist in the arrays.
The second result will contain, all occurrences of each number in the result
int[] a = [1,2,3,4,5];
int[] b = [1,2,3,4,5,6];
int[] c = [1,3,7];
int[] d = [2,3,4,8,9,10];
int[] result1 = [1,2,3,4,5,6,7,8,9,10];
int[] result2 = [1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,7,8,9,10];
Step 1: Combine all the arrays
Step 2: Sort arrays using Arrays.sort(array);
Step 3: Remove the duplicates.
int[] a = {1,2,3,4,5};
int[] b = {1,2,3,4,5,6};
int[] c = {1,3,7};
int[] d = {2,3,4,8,9,10};
int[] resultArray1 = new int[a.length+b.length+c.length+d.length];
int arrayIndex = 0;
for (int i=0; i< a.length ; i++, arrayIndex++ )
{
resultArray1[arrayIndex] = a[i];
}
for (int i=0; i< b.length ; i++, arrayIndex++ )
{
resultArray1[arrayIndex] = b[i];
}
for (int i=0; i< c.length ; i++, arrayIndex++ )
{
resultArray1[arrayIndex] = c[i];
}
for (int i=0; i< d.length ; i++, arrayIndex++ )
{
resultArray1[arrayIndex] = d[i];
}
// Sorting Arrays
System.out.println("Array before Sort"+Arrays.toString(resultArray1));
Arrays.sort(resultArray1);
System.out.println("Array after Sort"+Arrays.toString(resultArray1));
// Removing duplicates
Set<String> set = new HashSet<String>();
for (int i = 0; i < resultArray1.length; i++) {
set.add(""+resultArray1[i]); // To convert to string
}
String[] uniqueStringArray = set.toArray(new String[set.size()]); ;
int [] uniqueIntArray = new int [uniqueStringArray.length];
// Converting string array to int array
for(int i=0;i<uniqueStringArray.length;i++)
{
uniqueIntArray[i]= Integer.parseInt(uniqueStringArray[i]);
}
Arrays.sort(uniqueIntArray);
System.out.println("Unique Array after Sort"+Arrays.toString(uniqueIntArray));
Output:
Array before Sort[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 3, 7, 2, 3, 4, 8, 9, 10]
Array after Sort[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10]
Unique Array after Sort[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Combine all 4 arrays in 1 array
sort Array
Remove Dublicate from array
import java.util.Vector;
class sort
{
public static void main(String args[])
{
int[] a = {1,2,3,4,5};
int[] b = {1,2,3,4,5,6};
int[] c = {1,3,7};
int[] d = {2,3,4,8,9,10};
int[] s = combine(a,b,c,d); //concate array using concate function
int[] sort = sort(s);//sort array using sort function
//SORTING ARRAY
System.out.print("ARRAY AFTER SORT ");
System.out.print("[");
for(int i=0;i<sort.length;i++)
{
if(i==sort.length-1)
System.out.print(sort[i]);
else
System.out.print(sort[i]+",");
}
System.out.println("]\n");
//REMOVE DUPLICATE
int[] removedups=removedups(sort);// Remove Duplicate item from array using removedups
System.out.print("ARRAY REMOVE DUPLICATE ");
System.out.print("[");
for(int i=0;i<removedups.length;i++)
{
if(i==removedups.length-1)
System.out.print(removedups[i]);
else
System.out.print(removedups[i]+",");
}
System.out.print("]");
}
public static int[] combine(int a[],int b[],int c[],int d[])//combine array
{
int sort []=new int[a.length+b.length+c.length+d.length];
int j=0;
for(int i=0;i<a.length;i++)
{
sort[j]=a[i];
j++;
}
for(int i=0;i<b.length;i++)
{
sort[j]=b[i];
j++;
}
for(int i=0;i<c.length;i++)
{
sort[j]=c[i];
j++;
}
for(int i=0;i<d.length;i++)
{
sort[j]=d[i];
j++;
}
return sort;
}
public static int[] sort(int s[]) // sort array
{
int temp;
for(int i=0;i<s.length;i++)
{
for(int j=i+1;j<s.length-1;j++)
{
if(s[i]>s[j])
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
return s;
}
public static int[] removedups(int s[])//remove dups from sorted array
{
Vector array=new Vector();
int l=0;
for(int i=0;i<s.length-1;i++)
{
if(s[i]!=s[i+1])
{
array.add(s[i]);
l++;
}
}
int[] temp=new int[array.size()];
for(int j=0;j<temp.length;j++)
{
temp[j]=Integer.parseInt(""+array.get(j));
}
return temp ;
}
}//end the program
Simpliest way is use sort and HashSet
public class SortClass {
public static void main(String[] args) {
//Define imput data
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5, 6};
int[] c = {1, 3, 7};
int[] d = {2, 3, 4, 8, 9, 10};
//Actual algorithm
List<Integer> all = new ArrayList<Integer>();
all.addAll(toList(a));
all.addAll(toList(b));
all.addAll(toList(c));
all.addAll(toList(d));
Collections.sort(all);
TreeSet<Integer> set = new TreeSet<Integer>();
set.addAll(all);
int[] sorted = toIntArray(all);
int[] sortedUniq = toIntArray(set);
//Output result
System.out.println("Sorted: " + Arrays.toString(sorted));
System.out.println("Sorted uniq: " + Arrays.toString(sortedUniq));
}
// We need pair of method to convert between `int[]` and `Collection<Integer>`
private static int[] toIntArray(Collection<Integer> all) {
int[] ints = new int[all.size()];
int i =0;
for (int val : all) {
ints[i] = val;
i++;
}
return ints;
}
private static Collection<? extends Integer> toList(int[] ints) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i : ints) {
list.add(i);
}
return list;
}
}
But if performance is critical we can utilize the fact that input arrays already sorted and us merge sort:
public class SortClass {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5, 6};
int[] c = {1, 3, 7};
int[] d = {2, 3, 4, 8, 9, 10};
//Prepare data structure
List<ArrayTail> all = new ArrayList<ArrayTail>();
add(all, new ArrayTail(a));
add(all, new ArrayTail(b));
add(all, new ArrayTail(c));
add(all, new ArrayTail(d));
int[] sorted = sort(all);
int[] sortedUniq = getUniq(sorted);
System.out.println("Sorted: " + Arrays.toString(sorted));
System.out.println("Sorted uniq: " + Arrays.toString(sortedUniq));
}
private static int[] getUniq(int[] sorted) {
Collection<Integer> result = new ArrayList<Integer>();
int current = sorted[0];
result.add(current);
for (int i : sorted){
if(i != current){
current = i;
result.add(i);
}
}
return toIntArray(result);
}
private static int[] sort(List<ArrayTail> all) {
int totalLength = 0;
for (ArrayTail tail : all){
totalLength+=tail.size();
}
int[] result = new int[totalLength];
int pos = 0;
while(!all.isEmpty()){
//Take smallest value from smallest array
ArrayTail smallest = all.get(0);
result[pos] = smallest.take();
pos++;
// remove array if no more elements in it
if(smallest.size() ==0){
all.remove(0);
} else {
// ensure that first element steel smallest
sortFirstElement(all);
}
}
return result;
}
// This is actually on step of bubble sort, but it
// works because all other list except may be first already sorted
private static void sortFirstElement(List<ArrayTail> all) {
for (int i = 0; i < all.size()-1; i++) {
if(all.get(i).get() > all.get(i+1).get()){
Collections.swap(all, i, i + 1);
} else {
break;
}
}
}
private static void add(List<ArrayTail> all, ArrayTail arrayTail) {
// all sorted here
all.add(0, arrayTail);
sortFirstElement(all);
// all sorted here, again
}
private static int[] toIntArray(Collection<Integer> all) {
int[] ints = new int[all.size()];
int i =0;
for (int val : all) {
ints[i] = val;
i++;
}
return ints;
}
// Simpl data structure representing tail of array
private static class ArrayTail {
private final int[] arr;
private int pos;
public ArrayTail(int[] arr) {
this.arr = arr;
this.pos = 0;
}
public int size() {
return arr.length - pos;
}
public int take() {
return arr[pos++];
}
public int get() {
return arr[pos];
}
}
}
As you can see code become more complex but possible work faster.
PS: fun thing is that bubble sort can be used in real life :)
TRY Using merge sort algorithm. wikipedia page here
For result 1, dump the contents of your 4 lists into a TreeSet. This will sort and remove duplicates from the set at the same time. Then get the array of the set.
For result 2, use array copy to copy all the numbers into 1 array and then sort that array using Arrays.sort(...). There is no need to try to merge them on your own due to the nature of the sorting algorithm which is O(nlog(n)). Quadrupling the size results in a multiplying factor of only 2.

Java Adding 2 arrays together and return the sum of it

I am trying to add 2 arrays together and return the sum of it, but it doesn't produce any output. I wonder why?
public class MyProgram
{
public static void main (String[] args)
{
new MyProgram().start();
}
public void start()
{
int[] ar1 = {3, 8, 4, 9, 5, 5, 23, 14};
int[] ar2 = {33, 23, 41, 9, 17, 51, 23, 45};
sumA(ar1, ar2);
}
private int[] sumA(int[] ar1, int[] ar2)
{
int[] sumArray = new int[0];
for (int i = 0; i < ar1.length; i++)
{
sumArray[i] = ar1[i] + ar2[i];
}
return sumArray;
}
}
First, you need to instantiate the array correctly:
int[] sumArray = new int[ar1.length];
Then, if you want to see what is the result, you need to do something with it (print it maybe...):
System.out.println( Arrays.toString( sumA(ar1, ar2)) );
If you want to add arrays with different lengths:
private static int[] sumA(int[] ar1, int[] ar2) {
int[] sumArray = new int[Math.max(ar1.length, ar2.length)];
for (int i = 0; i < sumArray.length; i++) {
sumArray[i] = (i < ar1.length ? ar1[i] : 0) + (i < ar2.length ? ar2[i] : 0);
}
return sumArray;
}
If not, BobTheBuilder's answer is sufficient.
Your error is here:
int[] sumArray = new int[0]; <---
you need to instantiate the array with the length of one of the two parameters.
Try this:
int[] sumArray = new int[ar1.length];
or this
int[] sumArray = new int[ar2.length];
and if you want to show results:
int[] sumArray = new int[ar1.length];
for (int i = 0; i < ar1.length; i++)
{
sumArray[i] = ar1[i] + ar2[i];
System.out.print(sumArray[i] + " ");
}
return sumArray;
That's because you are not writing any system.out.println(); statements in your code. Try this code:
public class MyProgram
{
public static void main (String[] args)
{
new MyProgram().start();
}
public void start()
{
int[] ar1 = {3, 8, 4, 9, 5, 5, 23, 14};
int[] ar2 = {33, 23, 41, 9, 17, 51, 23, 45};
int sum[]=sumA(ar1, ar2);
for(int i: sum)
{
System.out.println(i);
}
}
private int[] sumA(int[] ar1, int[] ar2)
{
int[] sumArray = new int[8];
for (int i = 0; i < ar1.length; i++)
{
sumArray[i] = ar1[i] + ar2[i];
}
return sumArray;
}
}
See the image attached.

Categories

Resources