I have an array:
[0, 5, 6, 0, 0, 2, 5]
I would like to remove all zeros from it, so that this returns (keeping the same order):
[5, 6, 2, 5]
Is there any easier way to remove all zeros than the following?
int[] array = {0, 5, 6, 0, 0, 2, 5};
int len = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0)
len++;
}
int [] newArray = new int[len];
for (int i=0, j=0; i<array.length; i++){
if (array[i] != 0) {
newArray[j] = array[i];
j++;
}
}
I haven't been able to find any method in the Arrays class, and Google/SO searches didn't give me any good answers.
This is one of those rare cases where it is easier to show it in code than to explain in plain English:
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < array.length; sourceIndex++ )
{
if( array[sourceIndex] != 0 )
array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;
How about this:
Integer[] numbers = {1, 3, 6, 0, 4, 0, 3};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(numbers));
list.removeAll(Arrays.asList(Integer.valueOf(0)));
numbers = list.toArray(new Integer[list.size()]);
System.out.println(Arrays.toString(numbers));
OUTPUT:
[1, 3, 6, 4, 3]
With Java 8 you can make a stream out of the array, apply .filter() and then convert it back into an array :
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] filteredArray = Arrays.stream(array).filter(num -> num != 0).toArray();
// filteredArray = {5, 6, 2, 5};
You can achieve this with one loop only. Whether this is better or more clear is a matter of personal taste I am afraid.
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] temp = new int[array.length];
int numberOfZeros = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0){
temp[i-numberOfZeros] = array[i];
} else {
numberOfZeros++;
}
}
int[] result = new int[temp.length-numberOfZeros];
System.arraycopy(temp, 0, result, 0, result.length);
Another option would be to use a List implementation like ArrayList from which you can just remove elements, but then you will have to work with Integer instances and not with ints
List<Integer> originalList = ....;
Iterator<Integer> iterator = originalList.iterator();
while ( iterator.hasNext() ) {
Integer next = iterator.next();
if ( next == 0 ){
iterator.remove();
}
}
//convert to array if needed
Integer[] result = originalList.toArray( new Integer[originalList.size()]);
This example uses Apache Commons library , I hope this will be useful to you
import org.apache.commons.lang.ArrayUtils;
public class Test {
public static void main(String args[]) {
int[] array = {0, 5, 6, 0, 0, 2, 5};
// this loop is to remove all zeros
while(ArrayUtils.contains(array, 0))
array = ArrayUtils.removeElement(array, 0);
// this loop will print the array elemnents
for(int i : array)
System.out.println(i);
}
}
Does the programming language you use employ .map or .reduce functions, or is there an extension that allows you to do this?
In Swift, you can do this via .filter; observe
var orders = [0, 5, 6, 0, 0, 2, 5]
orders = orders.filter({ $0 != 0 })
print (orders)
This returns [5, 6, 2, 5], retaining your order
You can remove zeros in O(1) extra space. Instead of copying the elements into another array you can just return the size and print the same array:
public class RemoveZeros {
static int removeZeros(int[] a){
int j =0;
for(int i =0;i<a.length;i++) {
if(a[i] !=0) {
a[j] = a[i];
j++;
}
}
return j;
}
public static void main(String[] args) {
int[] a = new int[]{0, 5, 6, 0, 0, 2, 5};
int val = removeZeros(a);
for(int i =0;i<val;i++)
System.out.println(a[i]);
}
}
You can use a Vector:
Vector vec = new Vector();
for (int i=0; i<array.length; i++){
if (array[i] != 0)
vec.add(array[i]);
}
vec.toArray()
(this isn't the precise syntax, but you get the idea..)
If you are allowed to user List instead of array, you can do actually nothing but create a new Iteratable interface and apply a method to it like google-collections Collections2.filter() does, you can check it out.
Try the basic way:
public int[] convert(int[] data) {
int count =0;
for (int i =0; i< data.length; i++) {
if(data[i]==0)
count++;
}
int[] nonZero = new int[data.length-count];
int j =0;
for(int i = 0; i<data.length; i++) {
if(data[i]!=0) {
nonZero[j] = data[i];
j++;
}
}
return nonZero;
}
public class RemoveZeros {
public static void main(String[] args) {
int arr[] = {1,0,0,1,0,0,1,0,0,0,0,1,2,0,5};
int n = arr.length;
for(int i=0; i<n; i++) {
if(arr[i]!=0) {
System.out.print(arr[i]+ " ");
}
}
}
}
Related
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;
}
This is a pretty beginner assignment, and I would love to get some help with my code.
I need to combine two integer arrays into one using for loops, and make sure I don't have duplicates. Anything I googled is pretty over complicated and uses all sorts of built in methods.
Here is my code:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos] != array2[j]) {
merged[pos] = array2[j];
pos++;
}
}
System.out.println(Arrays.toString(merged));
Ultimately, it should return {1, 2, 3, 4, 5}. Instead, currently it returns 1, 2, 3, 3, 4, 5.
I would like to know why my if doesn't work. It should skip the 3 since it is already in there.
What am I missing?
Thanks :)
Edit:
Thanks guys, this is what I ended up doing, which still isn't good since I'm not checking for duplicates in the first loop that goes over the first array:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int arrSize = array1.length + array2.length;
int[] merged = new int[arrSize];
int pos = 0;
int counter = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos-1] != array2[j]) {
merged[pos] = array2[j];
pos++;
counter++;
}
}
int[] newMerged = new int[arrSize - counter + 1];
System.arraycopy(merged, 0, newMerged, 0, newMerged.length);
System.out.println(Arrays.toString(newMerged));
}
I'm sure I'll find a way.
I would like to know why my if doesn't work.
Because merged[pos] is always 0, because you've never assigned any other value to it in your code. Array entries are initialized to zero when you create the array.
You can't just check one entry to know whether to add a value from array2. You have to check all of the entries you've written, with a nested loop within your second for loop. Only add a new entry if it isn't already there.
Note that you'll also need to either check ahead of time how many duplicates there are so you know that merged should only be 5 entries long, or you need to re-create merged later when you know how long it should be. Otherwise, your end result will be {1, 2, 3, 4, 5, 0}, not {1, 2, 3, 4, 5}.
because of the "pos++" in the first for loop as you are using as start index of j in the second loop.
Your 3 is in the index 2 and you are comparing it to index 3, which never be equal
here is your answer:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0,i=0, j;
Set<Integer> intSet = new HashSet();
for (i = 0; i < array1.length; i++) {
if(!intSet.contains(array1[i])) {
merged[pos] = array1[i];
intSet.add(Integer.valueOf(i));
pos++;
}
}
for (j= 0, pos = pos-1; j < array2.length; ) {
if(!intSet.contains(Integer.valueOf(array2[j]))) {
merged[pos] = array2[j];
intSet.add(Integer.valueOf(i));
pos++;
j++;
}
}
System.out.println(Arrays.toString(merged));
Here is solution for Java 8 and bigger version:
int[] first = { 1, 2, 3 };
int[] second = { 3, 4, 5 };
int[] merged = Stream.of(first, second)
.flatMapToInt(Arrays::stream)
.distinct()
.toArray();
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;
}
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).
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]+" ");
}
}
}
}