Delete Duplicates From the Array - java

I need some help, guys.
Here is the assignment: Create a program to remove all the duplicates from a random array of integers. For example, if the array has the values
4, 7, 10, 4, 9, 5, 10, 7, 3, 5
then the array should be changed to
4, 7, 10, 9, 5, 3
The program should consist of two classes DeleteDuplicate and DeleteDuplicateDemo.
The DeleteDuplicate class should do the following
1. Have a method that checks for duplicate values.
2. Keep track of currentsize of array
3. Have a method that Delete duplicates (replace duplicate values with the next value in the array.)
The DeleteDuplicateDemo class should do the following
1. Have your main method.
2. Create a random array with a length of 10 numbers ranging from 1-10.
3. Display original random array.
4. Call(s) to DeleteDuplicate methods to find and remove duplicates.
5. Display new array without duplicates.
Sample Output:
[8, 5, 7, 3, 2, 5, 6, 3, 6, 7]
[8, 5, 7, 3, 2, 6]
Here is the code for DeleteDuplicateDemo:
import java.util.*;
public class DeleteDuplicateDemo
{
public static void main(String[] args)
{
Random random = new Random();
int array[]= new int[10];
for (int i = 0; i < array.length; i++)
{
array[i] = random.nextInt(10)+ 1;
}
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
DeleteDuplicate class1 = new DeleteDuplicate();
array = class1.removeDuplicates(array);
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
}
Here is the code for DeleteDuplicate:
import java.util.Arrays;
public class DeleteDuplicate
{
private static int[] remove(int[] array)
{
int current = array[0];
boolean found = false;
for (int i = 0; i < array.length; i++)
{
if (current == array[i] && !found)
{
found = true;
}
else if (current != array[i])
{
System.out.print(" " + current);
current = array[i];
found = false;
}
}
System.out.print(" " + current);
return array;
}
public static int[] removeDuplicates(int[] array) {
// Sorting array to bring duplicates together
Arrays.sort(array);
int[] finalArray = new int[array.length];
int previous = array[0];
finalArray[0] = previous;
for (int i = 1; i < array.length; i++){
int value = array[i];
if (previous != value){
finalArray[i] = value;
}
previous = value;
}
return finalArray;
}
}
How can I make it work? I only have a problem with calling another class. Thank you!

In your DeleteDuplicateDemo class, change
DeleteDuplicate class1 = new DeleteDuplicate();
array = class1.removeDuplicates(array);
to
array = DeleteDuplicate.removeDuplicates(array);
In your DeleteDuplicate class, change
for (int i = 1; i < array.length; i++){
int value = array[i];
if (previous != value){
finalArray[i] = value;
}
previous = value;
}
to
for (int i = 1, j = 0; i < array.length; i++){
int value = array[i];
if (previous != value){
finalArray[j] = value;
j++;
}
previous = value;
}
Then when you are printing out the values of array to the console the 2nd time, make sure to do a check for if array[i] != null before printing array[i].

Try this.
public static int[] removeDuplicates(int[] array) {
return IntStream.of(array).distinct().toArray();
}
test:
int[] array = {8, 5, 7, 3, 2, 5, 6, 3, 6, 7};
System.out.println(Arrays.toString(removeDuplicates(array)));
// -> [8, 5, 7, 3, 2, 6]

The removal code is too complex: rather than making a separate method for removing the item, walk through the array starting at index 1, and copy from the reading index into the writing index if the data that you write is different from the item at index i-1:
int rdIndex = 1;
int wrIndex = 1;
while (rdIndex != array.length) {
if (array[wrIndex-1] != array[rdIndex]) {
array[wrIndex++] = array[rdIndex];
}
rdIndex++;
}
return Arrays.copyOf(array, wrIndex);
At the end of the loop wrIndex indicates the number of items to be copied into the result array.
Demo.

Related

Checking if two int arrays have duplicate elements, and extract one of the duplicate elements from them

I'm trying to write a method, union(), that will return an int array, and it takes two int array parameters and check if they are sets, or in other words have duplicates between them. I wrote another method, isSet(), it takes one array argument and check if the array is a set. The problem is I want to check if the two arrays in the union method have duplicates between them, if they do, I want to extract one of the duplicates and put it in the unionArray[] int array. This is what I tried so far.
public int[] union(int[] array1, int[] array2){
int count = 0;
if (isSet(array1) && isSet(array2)){
for (int i = 0; i < array1.length; i++){
for (int j = 0; j < array2.length; j++){
if (array1[i] == array2[j]){
System.out.println(array2[j]);
count ++;
}
}
}
}
int[] array3 = new int[array2.length - count];
int[] unionArray = new int[array1.length + array3.length];
int elementOfUnion = 0;
for (int i = 0; i< array1.length; i++){
unionArray[i] = array1[i];
elementOfUnion = i + 1 ;
}
int index = 0;
for (int i = elementOfUnion; i < unionArray.length; i++){
unionArray[i] = array3[index];
index++;
}
return unionArray;
}
public boolean isSet(int[] array){
boolean duplicates = true;
for (int i = 0; i < array.length; i++){
for(int n = i+1; n < array.length; n++){
if (array[i] == array[n])
duplicates = false;
}
}
return duplicates;
}
What I was trying to do is to use all of array1 elements in the unionArray, check if array2 has any duplicates with array1, and then move all the non-duplicate elements from array2 to a new array3, and concatenate array3 to unionArray.
It will be much easier to do it with Collection API or Stream API. However, you have mentioned that you want to do it purely using arrays and without importing any class, it will require a few lengthy (although simple) processing units. The most important theories that drive the logic is how (given below) a union is calculated:
n(A U B) = n(A) + n(B) - n(A ∩ B)
and
n(Only A) = n(A) - n(A ∩ B)
n(Only B) = n(B) - n(A ∩ B)
A high-level summary of this solution is depicted with the following diagram:
Rest of the logic has been very clearly mentioned through comments in the code itself.
public class Main {
public static void main(String[] args) {
// Test
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4, 5, 6 }));
display(union(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 1, 2, 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 4, 5 }));
display(union(new int[] { 1, 2, 3, 4, 5, 6 }, new int[] { 7, 8 }));
}
public static int[] union(int[] array1, int[] array2) {
// Create an array of the length equal to that of the smaller of the two array
// parameters
int[] intersection = new int[array1.length <= array2.length ? array1.length : array2.length];
int count = 0;
// Put the duplicate elements into intersection[]
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
intersection[count++] = array1[i];
}
}
}
// Create int []union of the length as per the n(A U B) = n(A) + n(B) - n(A ∩ B)
int[] union = new int[array1.length + array2.length - count];
// Copy array1[] minus intersection[] into union[]
int lastIndex = copySourceOnly(array1, intersection, union, count, 0);
// Copy array2[] minus intersection[] into union[]
lastIndex = copySourceOnly(array2, intersection, union, count, lastIndex);
// Copy intersection[] into union[]
for (int i = 0; i < count; i++) {
union[lastIndex + i] = intersection[i];
}
return union;
}
static int copySourceOnly(int[] source, int[] exclude, int[] target, int count, int startWith) {
int j, lastIndex = startWith;
for (int i = 0; i < source.length; i++) {
// Check if source[i] is present in intersection[]
for (j = 0; j < count; j++) {
if (source[i] == exclude[j]) {
break;
}
}
// If j has reached count, it means `break;` was not executed i.e. source[i] is
// not present in intersection[]
if (j == count) {
target[lastIndex++] = source[i];
}
}
return lastIndex;
}
static void display(int arr[]) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i < arr.length - 1 ? arr[i] + ", " : arr[i]);
}
System.out.println("]");
}
}
Output:
[1, 2, 5, 6, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
Using Java's streams could make this quite simpler:
public int[] union(int[] array1, int[] array2) {
return Stream.of(array1, array2).flatMapToInt(Arrays::stream).distinct().toArray();
}
Even with all the restrictions of only using arrays, you can simplify your code a lot. No need to check for sets. Just :
allocate an array to store all elements of the union (i.e., int[] tmp_union ), which at worst will be all elements from both arrays array1 and array2.
iterate over the elements of array1 and compared them against the elements from tmp_union array, add them into the tmp_union array only if they were not yet added to that array.
Repeat 2) for the array2.
During this process keep track of the number of elements added to the tmp_union array so far (i.e., added_so_far). In the end, copy the elements from the tmp_union array into a new array (i.e., unionArray) with space allocated just for the union elements. The code would look something like:
public static int[] union(int[] array1, int[] array2){
int[] tmp_union = new int[array1.length + array2.length];
int added_so_far = add_unique(array1, tmp_union, 0);
added_so_far = add_unique(array2, tmp_union, added_so_far);
return copyArray(tmp_union, added_so_far);
}
private static int[] copyArray(int[] ori, int size) {
int[] dest = new int[size];
for(int i = 0; i < size; i++)
dest[i] = ori[i];
return dest;
}
private static int add_unique(int[] array, int[] union, int added_so_far) {
for (int element : array)
if (!is_present(union, added_so_far, element))
union[added_so_far++] = element;
return added_so_far;
}
private static boolean is_present(int[] union, int added_so_far, int element) {
for (int z = 0; z < added_so_far; z++)
if (element == union[z])
return true;
return false;
}

Add up each element in two uneven arrays in Java

Im Swedish so maybe I did give the wrong title.
I have two arrays of different size:
{2, 5, 10, 13}
{5, 7, 5, 22, 44, 75}
I want to add each element and put it in a third array.
So the result should be {7, 12, 15, 25, 44, 75}
I have manage to done some code.
I get an exeption of out of bounds.
I think the problem is that I can´t add a non existing element.
But how can I solve it?
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
for(int i=0; i < svar.length; i++)
System.out.println("Ny Array " + svar[i]);
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int sum = samling.length + samling2.length;
int[] total = new int[sum];
for(int i=0; i < total.length; i++){
//if (samling2.length != 0) // || samling.length != 0)
total[i] = samling[i] + samling2[i];
}
return total;
}
The length of the output array shouldn't be the sum of lengths of the input arrays, it should be the length of the longer input array. And before accessing an element of either input array, you must check the current index i is a valid index of that array.
public static int[] concateArrays(int[] samling, int[] samling2)
{
int[] total = new int[Math.max(samling.length,samling2.length)];
for(int i=0; i < total.length; i++) {
total[i] = (i < samling.length ? samling[i] : 0) +
(i < samling2.length ? samling2[i] : 0);
}
return total;
}
You can use one loop to loop over both arrays simultaneously.
You first need to check which array is the longest, and make a new array:
int[] arr = new int[longest];
Then you need to walk over the array. In this example, I assume the latter array is always the longest.
for (int i = 0; i < samling2.length; i++) {
int totalValue = samling[i];
if (i < samling.length) {
totalValue += samling2[i];
}
arr[i] = totalValue;
}
You can make an array of length equal to max of the two arrays you have. Then you can add the elements from both arrays if the specific index exist in both arrays else simply copy the index from the array which contain that index.
See the following code to get a better picture
import java.io.*;
class GFG {
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
System.out.println("Ny Array :");
for(int i=0; i < svar.length; i++)
System.out.print(svar[i] + " ");
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int len = 0;
if (samling.length > samling2.length)
len = samling.length;
else
len = samling2.length;
int[] total = new int[len];
for(int i=0; i < len; i++){
if (i >= samling2.length) {
total[i] = samling[i];
}else if( i >= samling.length) {
total[i] = samling2[i];
}else{
total[i] = samling2[i] + samling[i];
}
}
return total;
}
}
Another variant, with no need for a conditional operation in each iteration of the copying loop:
public static int[] concateArrays(int[] samling, int[] samling2)
{
// max length of the two arrays
int maxLen = Math.max(samling.length,samling2.length);
// decide which of the inputs is shorter and which is longer
int[] shorter = maxLen == samling.length ? samling2 : samling;
int[] longer = maxLen == samling.length ? samling : samling2;
int[] total = new int[maxLen];
// add both as long as there are elements in the shorter
for(int i=0; i < shorter.length; i++) {
total[i] = shorter[i] + longer[i];
}
// copy the remainder of the longer
for(int i=shorter.length; i < longer.length; i++) {
total[i] = longer[i];
}
return total;
}
You can try this :
public static int[] concateArrays(int[] samling, int[] samling2)
{
int minLength = samling.length;
int[] array = null;
if (samling2.length > samling.length) {
array = samling2;
} else {
minLength = samling2.length;
array = samling;
}
for (int i = 0; i < minLength; i++) {
array[i] = samling[i] + samling2[i];
}
return array;
}

Return indices of the two numbers such that they add up to a specific target

I have the below question I am trying to solve:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
I have the below array as input - [2, 7, 11, 15] with target = 9.
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
This is my code -
import java.util.Random;
public class TwoSum {
static int[] numbers = new int[] {2, 7, 11, 15};
int[] indices = new int[numbers.length];
public static int[] returnIndices(int target, int[] inputArr) {
int[] indices = new int[2];
int randomOne = new Random().nextInt(inputArr.length);
int randomTwo = new Random().nextInt(inputArr.length);
while(true) {
if(target == inputArr[randomOne] + inputArr[randomTwo]) {
indices[0] = randomOne;
indices[1] = randomTwo;
break;
}
}
System.out.println("done");
return indices;
}
public static void main(String[] args) {
int[] output = returnIndices(9, numbers);
}
}
Is this the right way to approach my problem?
You can use a hashmap to store the first array in the following manner:
key value(index in array)
2 - 0
7 - 1
11 - 2
15 - 3
Next get the target element which is 9, and start traversing your given array from index 0.
Element at index 0 is 2 --> calculate (9-2) = 7 --> check if 7 is a key in the hashmap
Additional Note: You need to take care of the following case:
arr = [3, 2, 1, 1] target = 6 (no answer exists in this case, but by the above method, when you calculate 6-3 = 3 you get index 0 as the answer.)
But this can easily be taken care of by checking whether (target-arr[i] == arr[i]) returns true or not. If it returns true and if the hashmap has two indices stored at the key arr[i], then return it as an answer, else proceed to the next element.
There are various ways to solve this question:
Hashmap way - #mettleap answer has covered that one.
Sort-Array way - I am going to explain its pseudo code to you.
Let us take an example to see it in action first. We are given arr = [5, 2, 1, 9, 7] elements in an array, and we are to find the indices of two elements if we can make 8.
If you look closely, then you will know if we sum 3rd + last element in an array, we will get 8, which means 2 and 4 would be our answer. So How would be land there? Let us go step by step
Maintain a separate array of the same size, it will hold the indices of arr in its initial setup.
[5, 2, 1, 9, 7] = arr
[0, 1, 2, 3, 4] = index_arr
Now sort arr in increasing order, and also sort the index_arr such that index of elements in arr in their initial setup is still in place.
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Use the below pseudo code:
low = 0
high = length of arr - 1
while (low < high) {
sum = arr[low] + arr[high]
if (sum == number) {}
print "index_arr[low]" and "index_arr[high]"
break the loop and exit
} else if ( sum < number ) {
low = low + 1
} else {
high = high - 1
}
}
Let us see psuedo code in action:
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Iteration # 01
low = 0 and high = 4
sum = arr[0] + arr[4] = 1 + 9 = 10
10 > 8 , means 'else' will be executed high = high - 1 = 4 - 1 = 3
Iteration # 02
low = 0 and high = 3
sum = arr[0] + arr[3] = 1 + 7 = 8
8 == 8 , means first 'if' condiion will execute, and will indices and exit the loop
Time Complexity - O(n)
Space Complexity - O(n)
I have tried it in c#, It may help..
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int[] result= TwoSumNumbers(nums, target);
}
public static int[] TwoSumNumbers(int[] nums, int target)
{
Dictionary<int, int> numsDict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int num = nums[i];
if (numsDict.TryGetValue(target - num, out int index))
{
return new[] { index, i };
}
numsDict[num] = i;
}
return null;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] answer = new int[2];
Map<Integer,Integer> values = new HashMap<Integer,Integer>();
for ( int i=0; i < nums.length; i++){
values.put(nums[i],i);
}
for ( int i=0; i < nums.length; i++){
int val = target - nums[i];
Integer secondIndex = values.get(val);
if ( secondIndex != null && secondIndex != i){
answer[0] = i;
answer[1] = secondIndex;
return answer;
}
}
return answer;
}
}
C# Version
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace MyBasics
{
class ArrayIndexForTarget
{
public static void Main()
{
ArrayIndexForTarget find = new ArrayIndexForTarget();
int[] arr = new int[] { 9, 2, 3, 9, 10 };
int target = 11;
var result = find.IndexFinder(arr, target);
Console.ReadKey();
}
public int[] IndexFinder(int[]myArray,int target)
{
int[] arr = new int[2];
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int p=0; p < myArray.Length; p++)
{
int numberToFind = target - myArray[p];
if (dict.ContainsValue(numberToFind))
{
arr[0] = dict.FirstOrDefault(x => x.Value == numberToFind).Key;
arr[1] = p;
return arr;
}
else
{
dict.Add(p,myArray[p]);
}
}
return arr;
}
}
}
class Solution {
function twoSum($nums, $target) {
$lenght = count($nums);
$indices = array();
for($i = 0; $i<$lenght-1; $i++){
for($j=$i+1; $j<$lenght; $j++){
if(($nums[$i]+$nums[$j]) == $target){
$indices[] = $i;
$indices[] = $j;
return $indices;
}
}
}
} }
private static int[] findNumbersToAdd(int target, int[] array) {
int[] answer = {-1, -1};
int length = array.length;
for (int i = 0; i < length; i++) {
int var1 = array[i];
for (int j = i + 1; j < length; j++) {
int var2 = array[j];
if (var1 + var2 == target) {
answer[0] = i;
answer[1] = j;
break;
}
}
}
return answer;
}
Given you aren't focused on performance I would think a brute force approach would be fine. Here is a solution using streams and records.
record IndexPair(int index1, int index2) { };
IntStream.range(0, arr.length).boxed()
.flatMap(i1 -> IntStream.range(i1, arr.length)
.filter(i2 -> arr[i1] + arr[i2] == target)
.mapToObj(i2 -> new IndexPair(i1, i2))
.forEach(ip -> ...);
If you only want one solution then you could use findAny instead of forEach.
I tried this question and implement it using HashMap in Java and it works completely fine.
public class Solution {
public int[] twoSum(final int[] A, int B) {
HashMap<Integer,Integer> hm=new HashMap<>();
int index1=Integer.MAX_VALUE;
int index2=Integer.MAX_VALUE;
int diff=0;
for(int i=0;i<A.length;i++){
diff=B-A[i];
if(hm.containsKey(diff)){
index2=i;
index1=hm.get(diff);
return new int[] {index1+1,index2+1};
}else{
if(!hm.containsKey(A[i])){
hm.put(A[i],i);
}
}
}
// If Arrays doesnt have such pairs
if(index2 == (Integer.MAX_VALUE) || index1 == (Integer.MAX_VALUE)){
return new int[] {};
}
return new int[] {index1+1,index2+1};
}
}
here is a simple solution with 2 running loops,
assuming the following
you only need 2 numbers to get to the target.
the solution exists (therefor no need to validate).
public int[] TwoSum(int[] nums, int target) {
for (int i=0; i< nums.Length; i++){
for (int j=i+1; j< nums.Length; j++){
if (nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
public int[] sumofTwo(int[] numbers, int target)
{
int[] answer = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0 ; i < numbers.length ; i++)
{
if(map.containsKey(target - numbers[i]))
{
answer[0] = map.get(target - numbers[i]);
answer[1] = i;
return answer;
}
else
{
map.put(numbers[i],i);
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
int [] arr = {4,7,1,-3,2};
for(int i=0; i<arr.length-1; i++)
{
for(int j=0; j<=arr.length-2; j++)
{
if((arr[i]+arr[j+1])==6)
{
System.out.println("indices = "+"["+i +","+(j+1)+"]");
}
}
}
}
}

Java - Merge Two Arrays without Duplicates (No libraries allowed)

Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).

How to get unique items from an array?

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me.
I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
1, 2, 3, 4, 5
Every item from that array just once.
But how to get it?
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.
I'll post the Set<Integer> code:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.
In Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
Below code will print unique integers have a look:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
Simple Hashing will be far efficient and faster than any Java inbuilt function:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
DEMO
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
In JAVA8, you can simply use
stream()
and
distinct()
to get unique elements.
intArray = Arrays.stream(intArray).distinct().toArray();
There is an easier way to get a distinct list:
Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray); //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList)); //Distinct
Collections.sort(intList); //Optional Sort
intArray = intList.toArray(new Integer[0]); //Back to array
Outputs:
1 2 3 0 0 2 4 0 2 5 2 //Array
1 2 3 0 0 2 4 0 2 5 2 //List
1 2 3 0 4 5 //Distinct List
0 1 2 3 4 5 //Distinct Sorted List
0 1 2 3 4 5 //Distinct Sorted Array
See jDoodle Example
You could do it like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]
I don't know if you've solved your issue yet, but my code would be:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
To find out unique data:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
you can use
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
Here is my piece of code using counting sort (partially)
Output is a sorted array consiting of unique elements
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while
trying to solve a problem from HackerEarth
If you are a Java programmer, I recommend you to use this.
It will work.
public class DistinctElementsInArray {
//Print all distinct elements in a given array without any duplication
public static void printDistinct(int arr[], int n) {
// Pick all elements one by one
for (int i = 0; i < n; i++) {
// Check if the picked element is already existed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
// 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
int arrayLength = array.length;
printDistinct(array, arrayLength);
}
}
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}

Categories