Can anyone tell me the code in java about write a function which returns true for two arrays have same unique elements? Thanks!! | SoloLearn: Learn to code for FREE!

0

Can anyone tell me the code in java about write a function which returns true for two arrays have same unique elements? Thanks!!

public static boolean distinctValues(int[] tmp){ for (int i = tmp.length - 1; i > 0; i--) { for (int j = 1; j < i; j++) { System.out.println(j + ". " + tmp[i] + " and " + tmp[j] + " are " + (tmp[i] == tmp[j] ? "equal" : "not equal")); if (tmp[i] == tmp[j]) { return true; } } return false this is where I am stuck.i can't find a way to use two array having same unique elements..

4/1/2020 7:36:32 PM

Megha

9 Answers

New Answer

+1

Megha I think this is what you need: https://code.sololearn.com/cjYNZ796NldP/?ref=app

+1

Denise Roßberg Thank you. I have now solved it using length comparison.

0

Megha I think you can do it in two steps: 1. first check if one of the arrays has unique elements, if this not true, you return False 2. if it has unique elements, you then check if the two arrays have same elements, if so, return True else return False.

0

Megha You need to compare the values of two arrays, right? So you need two arrays as parameter. public static boolean distinctValues(int[] arr1, int[] arr2){ } For a better understanding: arr1 = 1 2 3 4 arr2 = 4 5 6 7 would return true because both arrays shares 4?

0

Megha In this you are checking in only one array... And what missing is 0th element checking i>=0 not only i>0 And start j=0, not from 1 And it prints return true when not unique elements so change true to false and false to true, if you need to return false when there is not unique elements... In below code. public static boolean distinctValues(int[] tmp){ for (int i = tmp.length - 1; i >=0; i--) { for (int j = 0; j < i; j++){ System.out.println(j + ". " + tmp[i] + " and " + tmp[j] + " are " + (tmp[i] == tmp[j] ? "equal" : "not equal")); if (tmp[i] == tmp[j]) { return true; } } } return false; }

0

maybe i don't understand what he means by 'same unique elements'. the arrays should 'have unique elements while having same elements' or 'share just one common element' ?

0

Write a function that returns `true` if two arrays have same number of unique elements. For example: - arr1 = [1, 3, 4, 4, 6], arr2 = [3, 5, 7] ==> false - arr1 = [9, 8, 7, 6], arr2 = [4, 4, 5, 1] ==> false - arr1 = [2], arr2 = [3, 3, 3, 3] ==> true

0

We have to show that two arrays have same unique elements and they return true while checking

-1

your distinctValues function seems incorrect. first you should include 0 to the iterators range, and if tmp[i] ==tmp[j] you should return False, this means that two elements with different index are equal! at the end you return True.