Java matching arrays - java

The method which takes two integer arrays. The method returns an integer array containing all the elements in array int[]a that are also present in array int[]b in their original sequential order in int[]a.
This is what it should output :
input: {1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 2, 10}, {3, 2, 7, 12, 3, 9, 5, 2}
output: {2, 3, 5, 7, 3, 9, 2}
input: {4, 7, 1, 6, 9, 2, 3, 1}, {8, 5, 2, 1, 9, 4}
output: {4, 1, 9, 2, 1}
I tried something like this just to test it out to get my head around it but I still couldn't.
public static void arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i <= s1.length; i++) {
for (int j = 0; j <= s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
break;
}
System.out.println(storage);
}
Test cases:
int [] m1 = {1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 2, 10};
int [] m2 = {3, 2, 7, 12, 3, 9, 5, 2};
System.out.println(Arrays.toString(arraysMatching(m1, m2)));
Should print out [2, 3, 5, 7, 3, 9, 2]

To add to Codors answer, have the method return int[]:
public static int[] arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<>();
//for (int i = 0; i <= s1.length; i++) {
//wrong. change <= to < or better:
for (int i : s1) {
//for (int j = 0; j <= s2.length; j++) {
//wrong. change <= to < or better:
for (int j : s2) {
if (j == i) {
storage.add(j);
break;
}
}
}
//if you can use streams do
//return storage.stream().mapToInt(i->(int)i).toArray();
//alternatively
int[] returnArray = new int[storage.size()];
for(int i=0; i< storage.size(); i++) {
returnArray[i]=storage.get(i);
}
return returnArray;
}
So you can use it with System.out.println(Arrays.toString(arraysMatching(m1, m2)));

To my understanding, the second break statement terminates the outer loop too early; furthermore, the indexing goes one step too far in both loop termination conditions. Change the implementation as follows.
public static void arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
System.out.println(storage);
}
Edit:
If the result is not to be printed but to be returned, the signature and the body have to be changed as follows.
public static ArrayList<Integer> arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
return storage;
}
Edit:
If the return type is required to be Integer[], the implementation has to be changed as follows.
public static Integer[] arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
int[] result = new int[storage.size()];
result = storage.toArray(result);
return result;
}
Edit:
If the return type is required to be int[] and no 'fancy stuff' for result conversion is desired, the code has to be changed as follows.
public static int[] arraysMatching(int[] s1, int[] s2) {
ArrayList<int> storage = new ArrayList<int>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
int[] result = new int[storage.size()];
for (int k = 0; k < storage.length(); k++) {
result[k] = storage.get(k);
}
return result;
}

Related

ArrayList Bubblesort with strings

The sorting is not working, it doesn't sort the names by the alphabet, I wrote a bubble sort algorithm with int and it worked fine. Can you help me? Is something wrong with the compareTo() method?
public ArrayList<FootballPlayer> sortByNames(ArrayList<FootballPlayer> pList)
{
FootballPlayer z;
for(int i=0; i<pList.size(); i++)
{
for(int j=0; j<pList.size()-i-1;j++)
{
if((pList.get(i).getName()).compareTo(pList.get(j+1).getName())>0)
{
z = pList.get(j);
pList.set(j, pList.get(j+1));
pList.set(j+1,z);
}
}
}
for(int i=0; i<pList.size(); i++)
{
System.out.print(pList.get(i).getName()+";");
System.out.println("");
}
return pList;
}
Your implementation is not BubbleSort! Check Bubble sort or event a bit more advanced Cocktail shaker sort.
public static void bubbleSort(List<String> pList) {
boolean done = false;
for (int i = pList.size(); !done; i--) {
done = true;
for (int j = 0; j + 1 < i; j++) {
if (pList.get(j).compareTo(pList.get(j + 1)) <= 0)
continue;
done = false;
String tmp = pList.get(j);
pList.set(j, pList.get(j + 1));
pList.set(j + 1, tmp);
}
}
}
Output:
List<String> pList = new ArrayList<>();
for (int i = 0; i < 10; i++)
pList.add(String.valueOf(i));
Collections.shuffle(pList);
System.out.println(pList); // [0, 6, 7, 9, 5, 8, 4, 1, 3, 2]
bubbleSort(pList);
System.out.println(pList); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Getting the Elements that has duplicates in an int array Java

This post - "Java + Count duplicates from int array without using any Collection or another intermediate Array", was also a sample exercise in my book at school, but what I want to do is get the elements that has duplicates without sorting it.
What I did is I removed the duplicates of arrays first, to get only the unique elements and then I compare it to the original array and count how many times the element has been found. But the problem is it doesn't print the correct elements which has duplicates.
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
the correct output should be: 7, 1, 4
but instead it outputs: 7, 6, 1
This is my codes:
//method for removing duplicates
public static int[] removeDuplicates(int[] n) {
int limit = n.length;
for(int i = 0; i < limit; i++) {
for(int j = i + 1; j < limit; j++) {
if(n[i] == n[j]) {
for(int k = j; k < limit - 1; k++) {
n[k] = n[k + 1];
}
limit--;
j--;
}
}
}
int[] uniqueValues = new int[limit];
for(int i = 0; i < uniqueValues.length; i++) {
uniqueValues[i] = n[i];
}
return uniqueValues;
}
//method for getting elements that has duplicates
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
int count = 0;
int limit = u.length;
for(int i = 0; i < u.length; i++) {
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
//main
public static void main(String[] args) {
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
//printing original values
System.out.print(Arrays.toString(num));
System.out.println();
int[] a = getDuplicatedElements(num);
System.out.print("Elements with Duplicates: " + Arrays.toString(a));
}
What's the error in my codes here? Please help thanks...
You have two issues:
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
System.out.println ("unique " + Arrays.toString (u));
int count = 0;
int limit = u.length;
for(int i = 0; i < limit; i++) { // you must use limit instead of u.length
// in order for the loop to terminate
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
i--; // you must decrement i after you find a unique element in u
// otherwise you'll be skipping elements in the u array
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
With those fixes, you'll get the expected output:
Elements with Duplicates: [7, 1, 4]
It's fairly simple when using a stream
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
List<Integer> list = Arrays.stream(num).boxed().collect(Collectors.toList());
list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).forEach(System.out::println);

Need to find and store the duplicate numbers in a array in another array but dont know how to put the duplicate's in another array

I have found out the duplicate numbers in the array "a" but could not store the duplicate ones in another array "b". Any help much appreciated!
Here is my code:
public static void main(String[] args) {
int[] a = {1,2,3,3,5,6,1,7,7};
int[] b={};
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i]==(a[j])){
System.out.println(a[j]);
}
}
}
Because the length of result is not know, I would like to use a ArrayList instead of an array :
int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7};
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j] && !b.contains(a[j])) {
b.add(a[j]);
System.out.println(a[j]);
}
}
}
System.out.println(b);//result : [1, 3, 7]
You can try finding duplicates in an array using collections framework too:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
int[] a = {1,2,3,3,5,6,1,7,7};
Set<Integer> set=new HashSet<Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i:a) {
if(!set.add(i)) {
list.add(i);
}
}
int[] b=new int[list.size()];
for (int i=0;i<list.size();i++) {
b[i] =list.get(i);
}
}
}
Here I have used the fact that sets do not allow duplicate and if set.add returns false, that means that element is already available in the set
We cannot change the size of Array once it is initialized. Here we do not know how many duplicates item will be in the Array.
EDIT -- This might be a better solution, my earlier solution was throwing ArrayIndexOutOfBoundException as indicated by #YCF_L --
import java.util.Arrays;
public class T {
public static void main(String[] args) {
//int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7}; //Set-1, provided by #YCF_L
int[] a = {1,1,3,3,5,6,1,7,7}; //Set-2, provided by OP
int[] b = {};
for (int i=0, k=0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i] == a[j]){
System.out.println(a[j]);
k = k+1;
int[] p = new int[k];
for(int x=0; x < b.length; x++) {
p[x] = b[x];
}
p[k-1] = a[i];
b = p;
}
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(removeDuplicates(b)));
}
public static int[] removeDuplicates(int[] a) {
boolean[] bArr = new boolean[1000];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (!bArr[a[i]]) {
bArr[a[i]] = true;
j++;
}
}
int[] b = new int[j];
int c = 0;
for (int i = 0; i < bArr.length; i++) {
if (bArr[i]) {
b[c++] = i;
}
}
return b;
}
}
Output with Set-1 :
[1, 3, 7]
[1, 3, 7]
Output with Set-2 :
[1, 1, 1, 3, 7]
[1, 3, 7]

returning an array of n numbers repeated into another array

Basically i have to return an array of n numbers repeated in an array into another array of length m.
my code so far:
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count = 0;
for(int j = 0; j < a.length; j++)
for(int i = 0; i < m.length; i++)
if( i == a[j]){
m[i] = count++;
}
}
return m;
} public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
Std.Out.println(i + "->" + b[i]);
} } }
this is the output im supposed to get
0->0
1->3
2->2
3->2
4->4
5->2
6->0
7->3
8->3
9->3
10->4
11->4
but im getting
0->0
1->21
2->16
3->23
4->27
5->29
6->0
7->20
8->25
9->15
10->28
11->22
what am i doing wrong?
I am not going to give you a different solution, but rather to show the mistakes in your code. If we go with the logic in your code, you have few mistakes:
1) count should be reset to 0 after first loop. Otherwise you will sum up the counts from the previous iterations.
2) count++ should be before the assignment, otherwise it will first assign and then increment. Or you could use ++count.
3) The first loop should be over i.
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count;
for(int i = 0; i < m.length; i++) {
count =0;
for(int j = 0; j < a.length; j++)
if( i == a[j]){
count++;
m[i] = count;
}
}
return m;
}
Regards.
This should solve it and do the job!
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int j = 0; j < a.length; j++) {
m[a[j]] += 1;
}
return m;
}
public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
System.out.println(i + "->" + b[i]);
}
}
}
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int i = 0; i < a.length; i++) //loop through a
if( i < M) //number check
m[a[i]]++; //add one to m at index a[i]
return m;
}
}
this is the right code for the method frequency, also checks to see if the number is in range.

Trying to find the sum of the last column

public class arsum
{
static int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
public int[] summing(int[][] array)
{
int index = 0;
int a[] = new int[array[index].length];
for (int i = 0; i < array[0].length; i++)
{
int sum = 0;
for (int j = 0; j < array.length; j++)
{
sum += array[j][i];
}
a[index] = sum;
System.out.println(sum);
}
return a;
}
public static void main(String[] args) {
new arsum().summing(myarray);
}
}
At the moment it prints out all 4 column sums, however I only want the last sum. I cannot figure out how to code it properly for any general array.
I am new to coding and have not totally figured everything out yet.
Try,
int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
int sum = 0;
for (int nums[] : myarray) {
sum += nums[nums.length - 1];
}
System.out.println(sum);
you can also use array indexing to print sum of last column as below:-
public static int summing(int[][] array)
{
int row = array.length;
int sum = 0;
for (int i = row - 1; i > row - 2; i--) {
int col = myarray[i].length;
for (int j = 0; j < col; j++) {
sum += array[i][j];
}
System.out.println(sum);
}
return sum;
}

Categories

Resources