I'm trying to check whether an array of arrays has any duplicate values. The end goal would be an if statement saying:
if (arr does NOT have duplicate values) {continue code}
int [][] arr = new int[3][2];
int [] x = new int[1];
arr[0][0] = 1;
arr[0][1] = 1;
arr[1][0] = 1;
arr[1][1] = 2;
arr[2][0] = 1;
arr[2][1] = 2;
x = arr.getUnique(); /I assume it'll use getUnique() but I can't even get that to work
Any help would be awesome! Thanks
Java has a HashSet you can use to have a collection without duplicates.
Find a way to convert your array into a HashSet and compare the number of their elements. If they have the same number of elements, each element in your array is unique, if the HashSet is smaller, it means some duplicates have been removed.
You could create a helper function of your own like this:
private static boolean arrayHasDuplicates(int[][] arr) {
for (int i = 0; i < arr.length; i++)
{
for (int y = 0; y < arr.length; y++)
{
if (arr[i].length != arr[y].length) continue;
if (i == y) continue;
boolean same = true;
for (int x = 0; x < arr[y].length; x++)
{
if (arr[i][x] != arr[y][x]) {
same = false;
break;
}
}
if (same) return same;
}
}
return false;
}
Related
I'm trying to make a method that counts the number of unique elements in an array. For example, if the array contains [1,2,3,4,5,1,5] there are 3 unique elements and my method should return the number 3.
This is what I´ve got so far:
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j ++) {
if (number[i] == number[j]) {
break;
}
}
if (i == j);
unique++;
}
return unique;
}
The method takes in the array number and an integer len (which is the length of the array).
But in this case: [1,2,3,4,5,1,5] my method would return 5, instead of 3. I somehow need to check if the number has been repeated before, and if not unique++.
You can create a frequency Map and then get the number of keys that have only one occurrence.
static int numberOfUniqueIntegers(int[] number) {
Map<Integer, Long> freq = Arrays.stream(number).boxed().collect(
Collectors.groupingBy(x -> x, Collectors.counting()));
return (int) freq.entrySet().stream().filter(e -> e.getValue().equals(1L))
.map(Map.Entry::getKey).count();
}
Demo
This one should work, just retain the elements already seen in a separate array :
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < len; i++){
if (!temp.contains(number[i]))
{
unique ++;
temp.add(number[i]);
}
}
return unique;
}
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
boolean isRepeated;
for (int i = 0; i < len; i++){
isRepeated = false;//setting to defalut value
int j;
for (j = 0; j < len; j ++) {
if(j == i) continue;
if (number[i] == number[j]) {
isRepeated = true;//if caught duplicate
break;
}
}
//if not caught duplicate then increment unique ++
if(!isRepeated) unique++;
}
return unique;
}
What wen wrong?
You have to match every value with everyother value which you did not as because you are just using an array and there is no way to figure if futures values had a match in past. So, you have to cover the length of array and check each value against every value in it. if it was to be written using java collections then it be would much simpler and with less time complexity
If you need to do this without using any additional space, e.g. a Set, then you have no option but to compare each element in the array against all others, an O(n^2) solution.
static int numberOfUniqueIntegers(int[] number, int len)
{
int unique = 0;
for (int i = 0; i < len; i++)
{
int j = 0;
for (; j < len; j++)
if (i != j && number[i] == number[j]) break;
if (j == len) unique++;
}
return unique;
}
If you can use additional space then are options that use a Set.
You can try this with O(2n) complexity
static int numberOfUniqueIntegers() {
//int[] abc = { 1, 2, 3, 4, 5, 1, 5 };
int[] abc = { 1, 1, 1 };
Map<Integer, Integer> st = new HashMap();
int unique = 0;
for (int i = 0; i < abc.length; i++) {
if (st.isEmpty() || st.containsKey(abc[i])) {
Integer vl = st.get(abc[i]);
st.put(abc[i], Objects.nonNull(vl) ? (vl + 1) : 1);
} else {
st.put(abc[i], 1);
}
}
for (int i : st.keySet()) {
if (st.get(i) == 1) {
unique = unique + 1;
}
}
System.out.println(st);
return unique;
}
The easiest way is to just use Set.
int[] s = { 1, 2, 1, 5, 3, 4, 5, 1, 1, 5 };
int count = numberOfUniqueIntegers(s);
System.out.println("Count = " + count);
Prints
Count = 3
Set#add returns false if element exists, true otherwise
if seen doesn't contain it, add to unique.
if it has already been seen, remove from unique.
only the unique ones will remain.
static int numberOfUniqueIntegers(int[] number) {
Set<Integer> seen = new HashSet<>();
Set<Integer> unique = new HashSet<>();
for (int i : number) {
if (!seen.add(i)) {
unique.remove(i);
continue;
}
unique.add(i);
}
return unique.size();
}
Due to the nature of Set the above works in O(n) and no explicit counting of elements needs to be done.
Normally asking questions like this, many stack overflow answers will give you solutions, however, that might not be conducive to working through the problem yourself.
Keep in mind there are multiple ways to solve this kind of problem.
Use a Set (a data structure to deal specifically to deal with uniques)
Sort and count. On duplicates, move on.
Just want to point out a potential issue with your code. You are using a terminator on your conditional clause if(i == j);
Your code will compile and run correctly, however it will simply check the comparison and run count++ every time. You will want to fix this clause.
The correct syntax should be
if (i == j) {
count++
}
Check comment for the exact lines:
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j ++) {
if (number[i] == number[j]) {
break;
}
}
if (i == j); // This comparison is always ignored.
unique++; // This line is always happening
}
return unique;
}
You can use set
public static int numberOfUniqueIntegers(int[] number, int len) {
Set<Integer> st = new HashSet();
int unique = 0;
for (int i = 0; i < len; i++) {
if (!st.add(number[i])) {
unique = unique - 1;
} else {
unique = unique + 1;
}
}
return unique;
}
I have a problem and the title actually sums it up perfectly. So i'll just go ahead and show you the code snippet.
So the methode generate, is generating an array, that is filled with numbers between 1 and 1000, including both. The length of the array is user input.
The next method, isPrime, is gonna conclude if its a prime number, so i can use those numbers with the true condition in another method. The generate method works but in isPrime i always get errors. If u can think of a better way, let me know please.
static int[] generate(int n) {
int[] arr = new int[n+1];
for(int x = 0; x <= n; x ++) {
int number = (int) (Math.random()* 999)+1;
arr[x] = number;
}
return arr;
}
static int isPrime(int p, final int q[]) {
boolean itIs = true;
//final int[] arr;
for(int r = 0; r <= p; r++) { // here it somehow states r is deadCode
for(int j = 2; j < q[r]; j++) {
if(q[r]%j == 0) {
itIs = false;
}
}
return q[r];
}
}
First, create a method to check a value is prime:
public boolean isPrime(int value) {
for (int i = 0; i < value / 2; i++) { // value / 2 is enough, doesn't need to check all values
if (value % i == 0) {
return false;
}
}
return true;
}
Then you check each value of array and put prime value to new array:
public int[] filterArray(int[] array) {
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (isPrime(array[i])) {
intList.add(array[i]);
}
}
Integer[] integerArray = intList.toArray(new Integer[intList.size()]);
int[] intArray = ArrayUtils.toPrimitive(integerArray);
return intArray;
}
Then you get the filtered prime array.
How can I get int a = 400; int b = 100; from 2-dimensional array 1000 x 1000 in Java, for example, mass[400][100] (row 400, column 100)? I found element in array and need numbers of his row/line and column. How can I get this numbers? Thanks.
Are you asking how to get the dimensions of an array?
If a is new int[400][100]; then you can get 400 by doing a.length and 100 by doing a[0].length.
If you need to find the position in the array based on the value, you have no other option but to brute-force loop through the whole array, breaking out when you find the first match:
int[][] massiveArray = new int[1000][1000];
final int valueTofind = 27;
// assign the value to find at position (400, 100)
massiveArray[400][100] = valueTofind;
int i_value = -1;
int j_value = -1;
// find the first occurrance of valueTofind by looping through the array
outer: for (int i = 0; i < massiveArray.length; i++) {
for (int j = 0; j < massiveArray[0].length; j++) {
if (massiveArray[i][j] == valueTofind) {
i_value = i;
j_value = j;
break outer;
}
}
}
System.out.println(String.format("First position for %d is at (%d, %d)",
valueTofind, i_value, j_value));
you can Work Around this .. To get a value in 2d array one way to do is
int[][] a = ...;
for (int r=0; r < a.length; r++) {
for (int c=0; c < a[r].length; c++) {
int value= a[r][c];
}
}
this is my practice before my upcoming test, I'm trying to make the user input a number. And all elements in array1 that is below the user's number, will be put in a new ArrayList.
and then I'm trying to print only the highest number in that ArrayList. If the user input is lower than all number in array1, it will return -1.
here is my code, however, when I put 920, it still returns -1, I think there's something wrong with my code to find highest number in ArrayList. Can you guys please tell me what is wrong?
static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};
public static int blabla(int[] a, int b) {
Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < array1.length; i++) { // this is to find all numbers in array1 that is below user's number, and add it to the ArrayList
if (b > array1[i]) {
al.add(array1[i]);
} // if
} // for
outerloop: // and this function below is to find maximum number in ArrayList
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright
static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};
public static int blabla(int[] a, int b) {
Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();
At this point, a1 is an empty array, so a1.length = 0, this loop never gets executed.
for (int i = 0; i < a1.length; i++) {
// this is to find all numbers in array1 that is below user's number,
// and add it to the ArrayList
if (b > a1[i]) {
al.add(a1[i]);
} // if
} // for
a1 is still empty there, the second loop won't do anything either.
// and this function below is to find maximum number in ArrayList
outerloop:
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright
What about this:
// Finds the greater value in values that is below maximum.
// Returns -1 if none is found.
public static int blabla(int[] values, int maximum) {
int best_value = -1;
for (int value : values) {
if (value < maximum && value > best_value) {
best_value = value;
}
}
return best_value;
}
You can replace int[] values by List<Integer> values if your values are in an ArrayList.
You can use this
Collections.max(arrayList);
To know more about read Javadoc for Collection.max
If you want to use an ArrayList you can check fro maximum with linear time by,
public static Integer getMaximum(List<Integer> coll) {
if (coll == null) {
return null;
}
Integer i = coll.get(0);
for (int t = 1; t < coll.size(); t++) {
Integer v = coll.get(i);
if (v != null && v > i) {
i = v;
}
}
return i;
}
Or, you could change that to a SortedSet<Integer> set = new TreeSet<Integer>(); then the maximum element is always set.last();
I would simplify your two for loops by this one:
for (int g = 0; g <=(al.size()-1); g++) { //for each value in your new array
d = (al.get(g)>d)? al.get(g):d; //is current value higher than previous? if not keep old one
}
Simple way to find the max in an array or arrayList (or any collection actually) without using built in methods such as .max
Int currentMax = 0
For (int i = 0; i < al.length; i++)
{
If al[i] > currentMax
{
CurrentMax = al[i]
}
}
Answered this from my phone so I apologize for bad indents, but you get the idea :)
hello guys i need to sort some elements of integer in an integer array and need to store the index of the sorted list
assume if the elements in array are
x[]= {10,20,40,70,80,50,30};
i need to get the index of the sorted order say in this case i need to get 4,3,5,2,6,0 (ascending) (array x starting from 0)
A simple way (not algorithmically clever) would be to make a new list (or array) of objects from the existing list that contains the value and the index:
class ValueAndIndex implements Comparable<ValueAndIndex> {
final int value;
final int index;
ValueAndIndex(int value, int index) {
this.value = value;
this.index = index;
}
#Override public int compareTo(ValueAndIndex other) {
// compare on value;
if (this.value < other.value) {
return -1;
} else if (this.value > other.value) {
return 1;
} else {
return 0;
}
}
}
Now, create instances of this class in a list:
List<ValueAndIndex> secondaryList = new ArrayList<ValueAndIndex>(x.length);
for (int i = 0; i < x.length; ++i) {
secondaryList.add(new ValueAndIndex(x[i], i));
}
Sort this list:
Collections.sort(secondaryList);
Now, the indices are still in this list:
int [] indexesInSortedOrder = new int[x.length];
for (int i = 0; i < secondaryList.size(); ++i) {
indexesInSortedOrder[i] = secondaryList.get(i).index;
}
System.out.println(Arrays.toString(indexesInSortedOrder));
Possible solution
//sort the array intio a new array
y[] = x;
Arrays.sort(y); //sort ascending
//final array of indexes
int index_array[] = new int[7];
//iteretate on x arrat
for(int i=0; i<7; i++)
//search the position of a value of the original x array into the sorted y array, store the position in the index array
index_array[i] = arrays.binarySearch(x,y[i]);
you can create an array
y[] = {0,1,2,3,4,5,6};
And ith any sorting algorithm, when you switching moving two elements in array x, do the same in array y
One way to do (what I understand) you need:
Determine the size n of the original array.
Create result array R and initialize its elements with 0 . . n-1
Finally implement one sort algorithm in the way that it sorts a copy(!) of your original array whilst also switching the elements in R
Example run:
Copied Result
Array
------------------
1. 2-3-1 0-1-2
2. 2-1-3 0-2-1
3. 1-2-3 2-0-1
public Map sortDecendingDFSGlobal() {
Map<String, Object> multiValues = new HashMap<String, Object>();
double[] dfs = this.global_dfs;
int[] index = new int[dfs.length];
for (int i = 0; i < dfs.length; i++) {
index[i] = i;//for required indexing
}
for (int i = 0; i < dfs.length; i++) {
//sorting dfsglobal in decending order
double temp = dfs[i];
double swap = dfs[i];
int swapIndex = i;
//keeping track of changing indexing during sorting of dfsglobal
int indStart = index[i];
int indSwap = index[i];
int number = i;
for (int j = i; j < dfs.length; j++) {
if (temp < dfs[j]) {
temp = dfs[j];
swapIndex = j;
indSwap = index[j];
number = j;
}
}
dfs[i] = temp;
dfs[swapIndex] = swap;
index[i] = indSwap;
index[number] = indStart;
}
//again sorting the index matrix for exact indexing
for (int i = 0; i < index.length - 1; i++) {
for(int j = i; j < index.length - 1; j++ )
{
if(dfs[j] == dfs[j + 1] && index[j] > index[j + 1])
{
int temp = index[j];
index[j] = index[j+1];
index[j + 1] = temp;
}
}
}
this.sortedDFS = dfs;
this.arrIndex = index;
multiValues.put("sorted", dfs);
multiValues.put("index", index);
return multiValues;
} //SortedDecendingDFSGlobal()