Check for more than one element in an array - java

By mode, I am checking if the array has duplicates. I checked similar queries down here but they addressed the question with answers containing ArrayList and HashMap. I am not familiar with them and trying to answer it with an array. My following code only works for 1 duplicate and unable to perform multiple duplicate detection.
public class Mode {
public static void main(String[] args) {
int[] num = {2,3,4,5,8,8,8,7,7,7};
int mode = mode(num);
System.out.println(mode);
}
public static int mode(int[] num){
for(int x=0; x < num.length; x++){
for(int y=x+1; y < num.length; y++){
if(num[x] == num[y]){
return num[x];
}
}
}
return num[0];
}
}

The method mode should return a HashSet that contains the duplicates and not an int. Also note that your inner loop is incorrect. You should do:
public static HashSet<Integer> mode(int[] num){
HashSet<Integer> dup = new HashSet<>();
for(int x=0; x < num.length; x++) {
for(int y=0; y < num.length; y++) {
if(num[x] == num[y] && x != y) {
dup.add(num[x]);
}
}
}
return dup;
}
This solution is O(n2). You can achieve a better solution if you:
Sort the array.
Travel on it (only one time), if num[i] == num[i + 1], it's a duplicate.
This solution is O(n*log(n)) - Sorting and traveling on the array only once.

If you want a list of all of the duplicates, this code will give you the answer. If you want just the numbers that are duplicated use the code from #Stefan.
import java.util.Arrays;
public class Mode {
public static void main(String[] args) {
int[] num = {2, 3, 4, 5, 8, 8, 8, 7, 7, 7};
int[] mode = mode(num);
int i;
System.out.print("The duplicates are: ");
for (i = 0; i < mode.length - 1; i++) {
System.out.print(mode[i] + ", ");
}
System.out.println(mode[i] + ".");
}
public static int[] mode(int[] num) {
int numberOfDuplicates = 0;
int[] duplicates = new int[num.length];
Arrays.sort(num);
for (int i = 1; i < num.length; i++) {
if (num[i - 1] == num[i]) {
duplicates[numberOfDuplicates++] = num[i];
}
}
return Arrays.copyOf(duplicates, numberOfDuplicates);
}
}

You need to return HashSet OR LinkedHashSet for mode method instead of single int.
The first for statement is INCORRECT. It must be
for (int x=0; x < num.length - 1; x++) //--- You used x < num.length
The source code can be like below
Set<Integer> result = new HashSet<Integer>();
for(int x=0; x < num.length - 1; x++) {
boolean duplicated = false;
for(int y=x+1; y < num.length; y++) {
if(num[x] == num[y]) {
duplicated = true;
break;
}
}
if (duplicated) result.add(num[x]);
}
return result;

Related

Compare and count in two arrays not in same order - Java

I need to count how many of the same digits are in the code vs. guess.
If code = [1, 2, 5, 6] and guess = [4, 1, 3, 2], it should return 2.
I can't directly change the parameter arrays, so I first created new arrays, sorted, then looped through to find how many are the same in both. The issue is that it returns 4 no matter what.
public static int digits(int[] code, int[] guess) {
int[] sortedCode = new int[code.length];
int[] sortedGuess = new int[guess.length];
int digits = 0;
for (int i = 0; i < code.length; i++) {
sortedCode[i] = code[i];
sortedGuess[i] = guess[i];
}
Arrays.sort(sortedCode);
Arrays.sort(sortedGuess);
for (int i = 0; i < code.length; i++) {
if (sortedGuess[i] == sortedCode[i]) {
digits++;
}
}
return digits;
As #Icarus mentioned in the comments, "you're comparing index to index when you should compare index to every index".
public static int getCorrectDigits(int[] code, int[] guess) {
int correctDigits = 0;
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
for (int x = 0; x<code.length; x++){
for (int y = 0; y<guess.length; y++){
if (code[x] == guess[y]){
correctDigits++;
}
}
}
return correctDigits;
}
You can also convert the traditional for loop to an enhanced for loop.
for (int j : code) {
for (int i : guess) {
if (j == i) {
correctDigits++;
}
}
}

Compare two Arrays and find the index where the arrays dont match anymore in JAVA

i have the following question.
I need to implement a Method to compare two Arrays and find the first index on which the elements of given arrays do not match.
I have tried the following code but its kinda weak:
public int UnmatchedElementsOnIndex(int[] x, int[] y) {
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < y.length; j++) {
if (x[i] == y[j]) {
// value is contained in both arrays
}
// otherwise not
}
return 0;
}
You can use java.lang.Arrays.mistmatch method to find the index of the first mismatch between two arrays of the same type. If no mismatch is found, it returns -1.
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 1, 2, 3, 4, 5, 3 };
Arrays.mismatch(a, b); // will return 5
This method will perform substantially better than custom code, since it compares data in the arrays in chunks.
You just have to scan through each element in the arrays. Then determine which element is not matching. The following is an one way to implement this.
public int UnmatchedElementsOnIndex(int[] x, int[] y) {
int index=-1;
//lengths should be equal. If not, we can't compare arrays
if(x.length!=y.length){
return -2;
}
for (int i = 0; i < x.length; i++) {
if (x[i] != y[i]) {
index=i;
break;
}
}
//returns -1, if all the elements are equal
return index;
}
Try this :
public int UnmatchedElementsOnIndex(int[] x, int[] y) {
// Also check for the list length
if(x.length < y.length)
return x.length;
else if(y.length < x.length)
return y.length;
for (int i = 0; i < x.length; i++) {
if(x[i] != y[i]) return i;
}
return -1;
}
It will return -1 if all elements in both arrays are the same, othewise return the first index when array not contain the same element in the same position.
public class Main {
public static void main(String args[]){
int a[]={15,5,85,7};
int b[] = {25,5,85,8};
UnmatchedElementsOnIndex(a,b);
}
public static void UnmatchedElementsOnIndex(int[] x, int[] y) {
int index=-1;
int[] array = new int[x.length];
int n=0;
for (int i = 0; i < x.length; i++) {
if (x[i] != y[i]) {
array[n]=i;
n++;
}
}
for(int i=0;i<n;i++){
System.out.println(array[i]);
}
}
}
public int UnmatchedElementsOnIndex(int[] x, int[] y) {
for (int i = 0; i < x.length && i < y.length; i++) {
if (x[i] != y[i]) {
return i;
}
return -1;
}
}

How do I remove duplicates from two arrays?

I need to have an algorithm that changes values in one array if it is in the second array. The result is that the first array should not have any values that are in the second array.
The arrays are of random length (on average ranging from 0 to 15 integers each), and the content of each array is a list of sorted numbers, ranging from 0 to 90.
public void clearDuplicates(int[] A, int[] B){
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
A[i]++;
}
}
My current code does not clear all of the duplicates. On top of that it might be possible it will creat an index out of bounds, or the content can get above 90.
Although your question is not very clear, this might do the job. Assumptions:
The number of integers in A and B is smaller than 90.
The array A is not sorted afterwards (use Arrays.sort() if you wish to
fix that).
The array A might contain duplicates within itself afterwards.
public void clearDuplicates(int[] A, int[] B) {
// Initialize a set of numbers which are not in B to all numbers 0--90
final Set<Integer> notInB = new HashSet<>();
for (int i = 0; i <= 90; i++) {
notInB.add(i);
}
// Create a set of numbers which are in B. Since lookups in hash set are
// O(1), this will be much more efficient than manually searching over B
// each time. At the same time, remove elements which are in B from the
// set of elements not in B.
final Set<Integer> bSet = new HashSet<>();
for (final int b : B) {
bSet.add(b);
notInB.remove(b);
}
// Search and remove duplicates
for (int i = 0; i < A.length; i++) {
if (bSet.contains(A[i])) {
// Try to replace the duplicate by a number not in B
if (!notInB.isEmpty()) {
A[i] = notInB.iterator().next();
// Remove the added value from notInB
notInB.remove(A[i]);
}
// If not possible, return - there is no way to remove the
// duplicates with the given constraints
else {
return;
}
}
}
}
You can do it just by using int[ ] although it's a bit cumbersome. The only constraint is that there may not be duplicates within B itself.
public void clearDuplicates(int[] A, int[] B) {
//Number of duplicates
int duplicate = 0;
//First you need to find the number of duplicates
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++)
if (A[i] == B[j])
duplicate++;
}
//New A without duplicates
int[] newA = new int[A.length-duplicate];
//For indexing elements in the new A
int notDuplicate = 0;
//For knowing if it is or isn't a duplicate
boolean check;
//Filling the new A (without duplicates)
for (int i = 0; i < A.length; i++) {
check = true;
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
check = false;
notDuplicate--;//Adjusting the index
}
}
//Put this element in the new array
if(check)
newA[notDuplicate] = A[i];
notDuplicate++;//Adjusting the index
}
}
public class DuplicateRemove {
public static void main(String[] args) {
int[] A = { 1, 8, 3, 4, 5, 6 };
int[] B = { 1, 4 };
print(clear(A, B));
}
public static int[] clear(int[] A, int[] B) {
int a = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
a++;
for (int k = i; k < A.length - a; k++) {
A[k] = A[k + 1];
}
}
}
}
int[] C = new int[A.length - a];
for (int p = 0; p < C.length; p++)
C[p] = A[p];
return C;
}
public static void print(int[] A) {
for (int i = 0; i < A.length; i++)
System.out.println("Element: " + A[i]);
}
}
Here is an example.. I compiled and its working. For any question just let me know :)
maybe you should try the following code:
public void clear (int[] A, int[] B)
{
for (int i=0; i<A.length;i++)
{
for (int j=0; j<B.length; j++)
if(A[i]==B[j])
{
for (int k=i; k<A.length;k++)
A[k]=A[k+1];
j=B.length-1; //so that the cycle for will not be executed
}
}
}

Adding the columns of a jagged 2D array

I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}

Manual reverse order in Array (Java)

Hello people of StackOverflow!
I have used the searrch option, I've found some related answers but none of them explained why this particular method of reverse ordering of an array in Java doesn't work:
class ReverseOrder
{
public static void main(String[] args)
{
int x[] = {1,2,3,4,5};
int y[] = x;
int i, j;
for(i = 0, j = x.length - 1; i < x.length; i++, j--)
{
y[i] = x[j];
}
for(int b = 0; b < x.length; b++)
{
System.out.println("Inverse order is: " + y[b]);
}
}
}
Why is the result 5,4,3,4,5 instead of 5,4,3,2,1??? It drives me absolutely insane and makes no sense to me. Any help would be greatly appreciated!
Because of this:
int y[] = x
y and x are now references to the same array. You should make sure you initialize y as a new array.
class ReverseOrder {
public static void main(String[] args)
{
int x[] = {1,2,3,4,5};
int y[] = new int[5]; // or you could use [x.length]
int i, j;
for(i = 0, j = x.length - 1; i < x.length; i++, j--)
{
y[i] = x[j];
}
for(int b = 0; b < x.length; b++)
{
System.out.println("Inverse order is: " + y[b]);
}
}
}
int y[] = x;
Makes y refer to the same data as x.
y[i] = x[j];
you are also modifying the input array x.
You want y to be totally independent:
int y[] = new int[x.length];
instead.
If you want to reverse the order of array elements in place (that is, modify the array x directly), you can iterate halfway through the array, swapping elements:
final int last = x.length - 1;
final int n_2 = x.length / 2; // round down for odd lengths
for (int i = 0; i < n_2; ++i) {
int tmp = x[i];
x[i] = x[last - i];
x[last - i] = tmp;
}

Categories

Resources