Arrays| Find repeating integers using array division? - java

How do I make the method show the repeated numbers. It seems a logical error that is stopping me and I don't know why the code doesn't do what it is supposed to do.
public static void findRepeating(int[] arr) {
for (int i = 0; i< arr.length; i++) {
for(int d = 0; d<arr.length; d++) {
if(arr[i] / arr[d] == 1) {
System.out.println(arr[i] + " is repeating");
}
}
}
}
public static void main(String[] args) {
int[] myArray = {69, 7, 8, 9, 90, 666, 69, 420, 2};
findRepeating(myArray);
}
}

Here is the correction, for the logic in inner for loop and the comparison
public static void findRepeating(int[] arr) {
for (int i = 0; i< arr.length; i++) {
for(int d = i+1; d<arr.length; d++) { //check with next element, as u will iterate over same element if iterating from start
if(arr[i] == arr[d]) { // checking for same number, as division can give 1 in multiple case for ex 11/7 is also 1
System.out.println(arr[i] + " is repeating");
}
}
}
}

Issue is with your if condition logic.
if (i != d && arr[i] / arr[d] == 1 && arr[i] % arr[d] == 0)
1) You should check that you are not dividing by the same array element. You can instead initialize the value of d from i+1 instead of 0.
2) Divide by should be equal to 1
3) There modulus should be 0 because division logic is not enough for this logic.
As #Eran said 9/8 and 9/9 will also result in 1 but with modulus check, we can ensure that we print that only 9 is repeating
public static void findRepeating(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int d = 0; d < arr.length; d++) {
if (i != d && arr[i] / arr[d] == 1 && arr[i] % arr[d] == 0) {
System.out.println(arr[i] + " is repeating");
}
}
}
}
public static void main(String[] args) {
int[] myArray = { 69, 7, 8, 9, 90, 666, 69, 420, 2 };
findRepeating(myArray);
}

The problem is already highlighted with your approach , but iterating over element again and again is not advisable when your array size is too high(time complexity of O(n^2) ) rather consider doing it as you iterate over the array in O(n) time with extra space of O(n)
Set<Integer> hs = new HashSet<Integer>(); // to store elements
for (int i = 0; i< arr.length; i++) {
if(hs.contains(arr[i])) { // Checking if element is present in set or not
System.out.println(arr[i] + " is repeating");
}else {
hs.add(arr[i]);
}
}
}

You need to exclude current i index from second loop condition. For a large optimalization, you could start iterating second loop from index i.
public static void findRepeating(int[] arr) {
if(arr.length<2) { return; } // edge case condition
for (int i = 0; i< arr.length; i++) {
for(int d = i+1; d<arr.length; d++) { // start from i+1 index
if( arr[i] == arr[d]) {
System.out.println(arr[i] + " is repeating");
}
}
}
}
Now it will print:
69 is repeating
Otherwise you will always print arr[i] as repeated.

Related

How to count duplicates in two unsorted arrays

I need to compare the guess and code arrays and count the number of correct digits in the guess.
It works until there are duplicate numbers in the code array. I know it's something to do with the second for loop and subtracting from the correctDigits.
public static int digits(int[] code, int[] guess) {
int digits = 0;
for (int i = 0; i < code.length; i++) {
for (int j = 0; j < guess.length; j++) {
if (guess[j] == code[i]) {
digits++;
break;
}
}
}
for (int i = 0; i < code.length; i++) {
for (int j = i + 1; j < code.length; j++) {
if (code[i] == code[j] && code[i] != guess[j] && code[j] != guess[i]) {
digits--;
}
}
}
return digits;
}
Since you mentioned "only using loops and basic knowledge" I assume concepts like maps are not included here and "basic knowledge" means "arrays".
If all you need to know is the number of digits try to convert your input to a 10-element array of counts, i.e. each digit would be the input.
Example:
int[] codeDigits = new int[10];
for (int i = 0; i < code.length; i++) {
codeDigits[code[i]]++;
}
This would turn [5,9,9,9] into [0,0,0,0,0,1,0,0,0,3], i.e. 5: 1x, 9: 3x
Now do this for the guess as well, e.g. [0,0,9,9] becomes [2,0,0,0,0,0,0,0,0,2].
Now all you have to do is count the number of digits:
int counter = 0;
for( int i = 0; i < codeDigits.length; i++ ) {
if( codeDigits[i] >= guessDigits[i] ) {
counter += guessDigits[i]; //guessed the exact number or less -> use the guess
} else {
counter += codeDigits[i]; //guessed more -> use the code
}
}
If you are able to use a Math function then the loop body could be replaced by counter += Math.min(codeDigits[i], guessDigits[i]);.
One more illustration (with longer codes to illustrate better):
code: [5,0,9,9,1,7,1] -> [1,2,0,0,0,1,0,1,0,2]
guess: [9,9,0,9,7,4,2] -> [1,0,1,0,1,0,0,1,0,3]
-----------------------------------------
minimum of each digit: 1,0,0,0,0,0,0,1,0,2
If you sum those minimums you get 4 correct digits: 1x 0, 1x 7, 2x 9
there are several solutions. one of them is indexing duplicated values of code array, then check them at first loop (and remove the 2nd loop):
int correctDigits = 0;
int[] duplicateIndexes = new int[code.length];
for (int i=0; i < code.length; i++) {
if( duplicateIndexes[i] == 1) continue;
for (int j=0; j < code.length; j++) {
if( core[i] == core[j]) {
duplicateIndexes[j] == 1;
continue;
}
}
}
for (int i = 0; i < code.length; i++) {
if (duplicatedIndexes[i] == 1) continue;
for (int j = 0; j < guess.length; j++) {
if (guess[j] == code[i]) {
correctDigits++;
break;
}
}
}
You can generate two Maps from these arrays, which associating a Value with its number of occurrences.
Then iterate over the entries of the Map obtained from the code array and compare its values with the corresponding values from the Map created based on the guess array. That would allow determining the number of correct/incorrect guesses.
I hope this will work.
Code
public static int getCorrectDigits(int[] code, int[] guess) {
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
int correctDigits = 0;
for (int i = 0; i < code.length; i++) {
if (guess[i] == code[i]) {
correctDigits++;
}
}
return correctDigits;
}
Output
Code - 5 9 9 9
Guess - 0 9 9 9
Passes - 3
Code - 5 9 9 9
Guess - 9 9 0 0
Passes - 1
Code - 5 9 9 9
Guess - 0 0 9 9
Passes - 2
Code - 5 9 9 9
Guess - 9 0 0 0
Passes - 0
You need to change the for loop to iterate over the guess instead of iterate over the code array:
public static int getCorrectDigits(int[] code, int[] guess) {
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
int correctDigits = 0;
for (int i = 0; i < guess.length; i++) {
for (int j = 0; j < code.length; j++) {
if (guess[i] == code[j]) {
correctDigits++;
break;
}
}
}
return correctDigits;
#Test
void ex1() {
assertEquals(3, ArrayComp.getCorrectDigits(new int[] {5,9, 9, 9}, new int[] {0,9,9,9}));
} #Test
void ex2() {
assertEquals(2, ArrayComp.getCorrectDigits(new int[] {5,9, 9, 9}, new int[] {9,9,0,0}));
} #Test
void ex3() {
assertEquals(2, ArrayComp.getCorrectDigits(new int[] {5,9, 9, 9}, new int[] {0,0,9,9}));
} #Test
void ex4() {
assertEquals(1, ArrayComp.getCorrectDigits(new int[]{5, 9, 9, 9}, new int[]{9, 0, 0, 0}));
}
I thought I'd join in on the fun - maintain a boolean array of code digits used, requires only one nested loop and reverse the looping order:
public static int getCorrectDigits(int[] code, int[] guess) {
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
int correctDigits = 0;
boolean[] used = new boolean[code.length];
for (int i = 0; i < guess.length; i++) {
for (int j = 0; j < code.length; j++) {
if (guess[i] == code[j] && !used[j]) {
correctDigits++;
used[j] = true;
break;
}
}
}
return correctDigits;
}

Getting StackOverFlow error while trying to code Merge Sort in Java

I am new to coding and I was trying to create merge sort algorithm in java. I am getting too many errors and I am not able to figure out the exact mistake
in the code.
I feel my logic is correct but don't know which step(s) is causing the error. Could someone help me rectify the mistakes in the following code.
Thank you
package com.company;
public class MergeSort_Array {
//Method created to print Input Array
public static void printInputArray(int inputArray[]) {
for (int i:inputArray) { //for-each loop
System.out.print(i + " ");
}
System.out.println();
}
//Function created to sort and merge Input Array:
public static void SortArray(int[] A) {
int midpoint = A.length / 2;
int[] left = new int[midpoint];
int[] right;
if (A.length % 2 == 0) {
right = new int[midpoint];
} else {
right = new int[midpoint + 1];
}
//Copying values from super Array to left Array:
for (int i = 0; i < midpoint; i++) {
left[i] = A[i];
}
//Copying elements from super Array to right Array:
for (int j = 0; j < right.length; j++) {
right[j] = A[midpoint + j];
}
//using Recursion
SortArray(left);
SortArray(right);
MergeArray(A, left, right);
}
// Creating a Function to merge left and right arrays.
public static void MergeArray(int[] result, int[] L, int[] R) {
//result array length = length of left array+ right array length
result = new int[L.length + R.length];
int i = 0, j = 0, k = 0;
while (k < result.length) {
if (L[i] < R[j]) {
result[k] = L[i];
i++;
} else
if (R[j] < L[i]) {
result[k] = R[j];
j++;
} else
if (i > L.length) {
while (j <= R.length) {
result[k] = R[j];
j++;
}
} else
if (j > R.length && i <= L.length) {
while (i <= L.length) {
result[k] = L[i];
i++;
}
}
k++;
}
}
public static void main(String[] args) {
int[] inputArray = { 2, 5, 4, 1, 7, 9, 6 };
MergeSort_Array ms = new MergeSort_Array();
ms.printInputArray(inputArray);
SortArray(inputArray);
for (int i: inputArray) {
System.out.println(i + " ");
}
}
}
Every time you call SortArray it will itself call SortArray twice. There is no end condition: every invocation will try to call SortArray twice.
This means that no call of SortArray can ever complete, since you infinitely recurse in each of them.
There must be some base case where it no longer calls itself. For mergesort one usually switches to some other algorithm once the array is small enough, but for simplicities sake you can even fall back to the most trivial base case for sorting: any array shorter than 2 elements is always sorted and needs nothing else to be done to be sorted.
There are multiple problems in your code:
[Major] SortArray() always attempts to split the array and sort both halves. You should not do this if the array length is less than 2, otherwise you get an infinite recursion causing a stack overflow exception.
[Hint] right can be initialized unconditionally as int[] right = new int[A.length - midpoint];
[Major] MergeArray should not reallocate the destination array. The merge must be performed in place into result so the caller's object is updated.
[Major] in the merge loop, you must test the index values before attempting to read L[i] or R[j], otherwise you might get an out of bounds exception.
Here is a modified version:
package com.company;
public class MergeSort_Array {
// Method created to print Input Array
public static void printInputArray(int inputArray[]) {
for (int i : inputArray) { //for-each loop
System.out.print(i + " ");
}
System.out.println();
}
//Function created to sort and merge Input Array:
public static void SortArray(int[] A) {
if (A.length >= 2) {
int midpoint = A.length / 2;
int[] left = new int[midpoint];
int[] right = new int[A.length - midpoint];
//Copying values from super Array to left Array:
for (int i = 0; i < midpoint; i++) {
left[i] = A[i];
}
//Copying elements from super Array to right Array:
for (int j = 0; j < right.length; j++) {
right[j] = A[midpoint + j];
}
//using Recursion
SortArray(left);
SortArray(right);
MergeArray(A, left, right);
}
}
// Creating a Function to merge left and right arrays.
public static void MergeArray(int[] result, int[] L, int[] R) {
for (int i = 0, j = 0, k = 0; k < result.length; k++) {
if (j >= R.length || (i < L.length && L[i] < R[j])) {
result[k] = L[i++];
} else {
result[k] = R[j++];
}
}
}
public static void main(String[] args) {
int[] inputArray = { 2, 5, 4, 1, 7, 9, 6 };
printInputArray(inputArray);
SortArray(inputArray);
printInputArray(inputArray);
}
}

Java sorting array positive ascending to negative ascending

I can't solve the problem , where I need output from array A like {1,2,3,4,-1,-2,-3,-4}
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String[] args) {
int a[] = {5,4,3,2,1,-3,-2,-30};
int length = a.length - 1;
for (int i = 0 ; i < length ; i++) {
for (int j = 0 ; j < length-i ; j++) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
for (int x : a) {
System.out.print(x+" ");
}
}
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String[] args) {
int a[] = {5,4,3,2,1,-3,-2,-30,-1,-15,8};
int length = a.length - 1;
for (int i = 0 ; i < length ; i++) {
for (int j = 0 ; j < length-i ; j++) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
} else {
if (a[j] > a[j+1] && a[j+1] > 0) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
}
for (int x : a) {
System.out.print(x+" ");
}
}
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
} else {
if (a[j] > a[j+1] && a[j+1] > 0) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer> {
public static void main(String args[]) {
int fullList[] = {5, 4, 3, 2, 1, -3, -2, -30};
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++) {
if (fullList[i] < 0) {
subList2.add((fullList[i]));
} else {
subList.add(fullList[i]);
}
}
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++) {
System.out.print(subList.get(i) + " ");
}
System.out.println("");
}
#Override
public int compare(Integer n1, Integer n2) {
return n2 - n1;
}
}
This will do the trick which uses only basic loops
public static void main(String[] args) {
int a[] = { 5, 4, 3, 2, 1, -3, -2, -30 };
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++) {
if (a[i] < 0)
neg++;
else
pos++;
}
// initialize the arrays based on 'pos' and 'neg'
int posArr[] = new int[pos];
int negArr[] = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++) {
if (a[i] < 0) {
negArr[countNeg] = a[i];
countNeg++;
} else {
posArr[countPos] = a[i];
countPos++;
}
}
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++) {
for (int j = 0; j < posArr.length - 1 - i; j++) {
if (posArr[j] > posArr[j + 1]) {
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
}
}
}
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++) {
for (int j = 0; j < negArr.length - 1 - i; j++) {
if (negArr[j] < negArr[j + 1]) {
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
}
}
}
// 1. print out posArr[] and then negArr[]
// or
// 2. merge them into another array and print
}
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
Positive numbers always come before negative numbers.
Positive numbers are ordered in ascending order.
Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> { // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0) {
return -1;
}
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0) {
return 1;
}
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else {
return (i < 0 ? j - i : i - j);
}
}
Your code could look like this:
int[] a = { 5, 4, 3, 2, 1, -3, -2, -30 };
int[] yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> { ... })
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.

How I can print largest sum in this Program?

package Message;
public class Example_R {
public static void main (String args[])
int n=1;
int input[]={1, 2, 1, 3, 4};
for (int j=0; j<=4; j++) {
int Add = 0;
for (int i=0; i<=4; i++) {
if (input[j] !=input[i]) {
Add+=input[i];
}
}
System.out.println(Add);
}
}
}
Output of This program is: 9 9 9 8 7 sum of all the other elements in the array that are not equal to the element.
Now I want to extend the program so I can print the Largest sum of any of it's element, (In this case 9 is the largest sum.) Do you have any suggestions? For this assignment I am restricted from using additional array, hashmap etc. not allowed. Arrays.sort(..)
Hint: use a variable that is holding "the largest sum reached so far". You will update it very time you compute a new sum.
You will need to find "how and when do I initialize this variable ?" and "how do I update it ?"
You probably want to create a separate method that you pass your "input[]" array to (left as an exercise). However when considering problems like this, first just consider how you would do it in english (or whatever your native language is). Write down that strategy (an "algorithm") and then implement that in Java.
public class Example_R {
public static void main(String args[]) {
int input[] = { 1, 2, 1, 3, 4 };
int largestSum = 0;
int currentSum;
for (int j = 0; j < input.length; j++) {
currentSum = 0;
for (int i = 0; i < input.length; i++) {
if (input[j] != input[i]) {
currentSum += input[i];
}
}
System.out.println("Sum of all values not equal to " + input[j]
+ " is: " + currentSum);
if (j == 0) {
largestSum = currentSum;
} else {
if (largestSum < currentSum) {
largestSum = currentSum;
}
}
}
System.out.println("The largest overall sum was " + largestSum);
}
}
You'll need a temporary variable to save the current highest number.
int temp = intArray[0]
for(int i : intArray)
{
if(i > temp)
temp = i;
}
Try this:
int n = 1,sum=0;
int[] input = { 1, 2, 1, 3, 4 };
for (int j = 0; j <= 4; j++){
int Add = 0;
for (int i = 0; i <= 4; i++){
if (input[j] != input[i])
Add += input[i];
}
if (sum < Add)
sum = Add;
}
After completing the second loop every time,the "sum" was updated if it is less than the current "add" value.
You can use variables of type Comparable and use the compareTo() method.
one.compareTo(two) will return > 0 if one > two
one.compareTo(two) will return < 0 if one < two
one.compareTo(two) will return 0 if one and two are equal
Go through the array, compare the current index with the previous index, and update a variable that holds the currentLargest value.

Efficient way to count unique pairs in int array

This is my first post, hope it complies with posting guidelines of the site.
First of all a generic thanks to all the community: reading you from some months and learned a lot :o)
Premise: I'm a first years student of IT.
Here's the question: I'm looking for an efficient way to count the number of unique pairs (numbers that appear exactly twice) in a given positive int array (that's all I know), e.g. if:
int[] arr = {1,4,7,1,5,7,4,1,5};
the number of unique pairs in arr is 3 (4,5,7).
I have some difficulties in... evaluating the efficiency of my proposals let's say.
Here's the first code I did:
int numCouples( int[] v ) {
int res = 0;
int count = 0;
for (int i = 0 ; i < v.length; i++){
count = 0;
for (int j = 0; j < v.length; j++){
if (i != j && v[i] == v[j]){
count++;
}
}
if (count == 1){
res++;
}
}
return res/2;
}
This shoudn't be good cause it checks the whole given array as many times as the number of elements in the given array... correct me if I'm wrong.
This is my second code:
int numCouples( int[] v) {
int n = 0;
int res = 0;
for (int i = 0; i < v.length; i++){
if (v[i] > n){
n = v[i];
}
}
int[] a = new int [n];
for (int i = 0; i < v.length; i++){
a[v[i]-1]++;
}
for (int i = 0; i < a.length; i++){
if (a[i] == 2){
res++;
}
}
return res;
}
I guess this should be better than the first one since it checks only 2 times the given array and 1 time the n array, when n is the max value of the given array. May be not so good if n is quite big I guess...
Well, 2 questions:
am I understanding good how to "measure" the efficiency of the code?
there's a better way to count the number of unique pairs in a given array?
EDIT:
Damn I've just posted and I'm already swamped by answers! Thanks! I'll study each one with care, for the time being I say I don't get those involving HashMap: out of my knowledge yet (hence thanks again for the insight:o) )
public static void main(String[] args) {
int[] arr = { 1, 4, 7, 1, 5, 7, 4, 1, 5 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
Integer count = map.get(arr[i]);
if (count == null)
map.put(arr[i], 1);
else
map.put(arr[i], count + 1);
}
int uniqueCount = 0;
for (Integer i : map.values())
if (i == 2)
uniqueCount++;
System.out.println(uniqueCount);
}
Well, here's another answer to your's 2 questions:
am I understanding good how to "measure" the efficiency of the code?
There are various ways to measure efficiency of the code. First of all, people distinguish between memory efficiency and time efficiency. The usual way to count all these values is to know, how efficient are the building blocks of your algorithm. Have a look at the wiki.
For instance, sorting using quicksort would need n*log(n) operations. Iterating through the array would need just n operations, where n is number of elements in the input.
there's a better way to count the number of unique pairs in a given array?
Here's another solution for you. The complixity of this one would be: O(n*log(n)+n), where O(...) is Big O notation.
import java.util.Arrays;
public class Ctest {
public static void main(String[] args) {
int[] a = new int[] { 1, 4, 7, 1, 7, 4, 1, 5, 5, 8 };
System.out.println("RES: " + uniquePairs(a));
}
public static int uniquePairs(int[] a) {
Arrays.sort(a);
// now we have: [1, 1, 1, 4, 4, 5, 5, 7, 7]
int res = 0;
int len = a.length;
int i = 0;
while (i < len) {
// take first number
int num = a[i];
int c = 1;
i++;
// count all duplicates
while(i < len && a[i] == num) {
c++;
i++;
}
System.out.println("Number: " + num + "\tCount: "+c);
// if we spotted number just 2 times, increment result
if (c == 2) {
res++;
}
}
return res;
}
}
public static void main(String[] args) {
int[] arr = {1,4,7,1,7,4,1,5};
Map<Integer, Integer> counts = new HashMap<Integer,Integer>();
int count = 0;
for(Integer num:arr){
Integer entry = counts.get(num);
if(entry == null){
counts.put(num, 1);
}else if(counts.get(num) == 1){
count++;
counts.put(num, counts.get(num) + 1);
}
}
System.out.println(count);
}
int [] a = new int [] {1, 4, 7, 1, 7, 4, 1, 5, 1, 1, 1, 1, 1, 1};
Arrays.sort (a);
int res = 0;
for (int l = a.length, i = 0; i < l - 1; i++)
{
int v = a [i];
int j = i + 1;
while (j < l && a [j] == v) j += 1;
if (j == i + 2) res += 1;
i = j - 1;
}
return res;
you can use HashMap for easy grouping. here is my code.
int[] arr = {1,1,1,1,1,1,4,7,1,7,4,1,5};
HashMap<Integer,Integer> asd = new HashMap<Integer, Integer>();
for(int i=0;i<arr.length;i++)
{
if(asd.get(arr[i]) == null)
{
asd.put(arr[i], 1);
}
else
{
asd.put(arr[i], asd.get(arr[i])+1);
}
}
//print out
for(int key:asd.keySet())
{
//get pair
int temp = asd.get(key)/2;
System.out.println(key+" have : "+temp+" pair");
}
added for checking the unique pair, you can delete the print out one
//unique pair
for(int key:asd.keySet())
{
if(asd.get(key) == 2)
{
System.out.println(key+" are a unique pair");
}
}
after some time another solution, which should work great.
public getCouplesCount(int [] arr) {
int i = 0, i2;
int len = arr.length;
int num = 0;
int curr;
int lastchecked = -1;
while (i < len-1) {
curr = arr[i];
i2 = i + 1;
while (i2 < len) {
if (curr == arr[i2] && arr[i2] != lastchecked) {
num++; // add 1 to number of pairs
lastchecked = curr;
i2++; // iterate to next
} else if (arr[i2] == lastchecked) {
// more than twice - swap last and update counter
if (curr == lastchecked) {
num--;
}
// swap with last
arr[i2] = arr[len-1];
len--;
} else {
i2++;
}
i++;
}
return num;
}
i am not shure if it works, but it is more effective than sorting the array first, or using hashmaps....
A Java8 parallel streamy version which uses a ConcurrentHashMap
int[] arr = {1,4,7,1,5,7,4,1,5};
Map<Integer,Long> map=Arrays.stream(arr).parallel().boxed().collect(Collectors.groupingBy(Function.identity(),
ConcurrentHashMap::new,Collectors.counting()));
map.values().removeIf(v->v!=2);
System.out.println(map.keySet().size());
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int arr[9] = {1,4,7,1,5,7,4,1,5}; // given array
int length=9; // this should be given
int count=0;
map<int,int> m;
for(int i=0;i<length;i++)
m[arr[i]]++;
cout<<"List of unique pairs : ";
for(auto it=m.begin();it!=m.end();it++)
if(it->second==2)
{
count++;
cout<<it->first<<" ";
}
cout<<"\nCount of unique pairs(appears exactly twice) : "<<count;
return 0;
}
OUTPUT :
List of unique pairs : 4 5 7
Count of unique pairs(appears exactly twice) : 3
Time Complexity : O(N) where N is the number of elements in array
Space Complexity : O(N) total no. of unique elements in array always <=N
var sampleArray = ['A','B','C','D','e','f','g'];
var count = 0;
for(var i=0; i<=sampleArray.length; i++) {
for(var j=i+1; j<sampleArray.length; j++) {
count++;
console.log(sampleArray[i] , sampleArray[j]);
}
}
console.log(count);
This is the simple way I tried.

Categories

Resources