Finding missing elements in arrays - java

My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
I have tried the following code, but it is not giving the right output.
public class MissingNumber {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 9, 9, 10 };
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
System.out.println("second array is : " + arr2[i]);
}
//compare two arrays i.e arr and arr2
for(int a=0;a<arr.length;a++){
for(int b=0;b<arr2.length;b++){
if(arr[a]==arr2[b]){
break;
}
else{
System.out.println("missing element is : "+arr[a]);
}
}
}
}
}
I want the number which is missing. Can anyone please let me know where I went wrong?

Check below code for if input array is any order or shuffled maner
public class MissingNumber {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 9, 9, 10};
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
}
for (int a = 0; a < arr2.length; a++) {
int count = 0;
for (int b = 0; b < arr.length; b++) {
if (arr2[a] == arr[b]) {
break;
} else {
count++;
}
}
if (arr2.length == count) {
System.out.println("missing element is : " + arr2[a]);
}
}
}
}

You are breaking out from the loop once there is a match from the 2 arrays. From the point of your logic, change it to (you don't need nested loops):
if(arr[a]!=arr2[a]){
System.out.println("missing element is : "+arr[a]);
break;
}
But if it is certain that the array is always in sequential order from 1 onwards, you don't need another array. Just do it as:
for(int x=0; x<arr.lengthl x++){
if(arr[x] != (x+1)){
System.out.println("Missing element is " + (x+1));
break;
}
}

Remove the second array, you don't need it and it might just lead to errors once you add elements to the original array.
Basically, replace your test by:
if(arr[a] != (a+1)){ System.out.println("Missing element: " + (a+1)); }
Don't break out of it, since there might be more elements missing.

You just broke the code when u found a correct match:
Just use the following:
if(arr[a] != arr2[b]){
System.out.println("missing element is : "+arr[a]);
break;
}
Or just replace break with continue

It is not working because you are looping through arr looking for any value that is not in arr2, and every element in arr IS in arr2. You want arr2 as the outer loop.

My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
It can also be done using just the array itself. Please note that it only works if one of the numbers is missing as specified in this question.
For Example,
Let Array be array = {1,2,3,4,5,6,7,9,9,10}.
Now, let us assume that Array will not always be sorted and hence the first step is to sort the array.
Arrays.sort(array);
Next step is to simply check the array's value at any given location, if the value != location + 1 then that is the missing number.
for(int x = 0; x < array.length; x++) {
if(array[x] != x + 1) {
System.out.println("Missing Entry: " + (x+1));
break;
}
}

Related

I am trying to compare two arrays inside For Loops

I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.
The piece of code I am having trouble with is in the method match() in the Lottery Class.
public void matches() {
PLAYER currentPlayer = pHead;
int count = 0;
for(int i = 0; i<6; i++) {
for(int j = 0; j< 6; j++) {
if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
count++;
}
}
}
``````````````````````````````````````````````````````````````````````````
Change the following snippet in matches():
if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
count++;
}
To
if (win.getWinningNumbers()[i] == currentPlayer.getNumbers()[j]) {
count++;
}
Maybe this example can help you a bit:
List<Integer> winningNumber = new LinkedList<>(Arrays.asList(3, 9, 15, 1, 11, 18));
List<Integer> playerNumbers = new LinkedList<>(Arrays.asList(2, 8, 15, 7, 11, 9));
matches(winningNumber, playerNumbers);
private static void matches(List<Integer> winningNumbers, List<Integer> playerNumbers) {
if(winningNumbers.size() != playerNumbers.size()) {
System.out.println("winning numbers and player numbers differ in size");
}
int counter = 0;
for(int i = 0; i < winningNumbers.size(); i++) {
if(winningNumbers.get(i) == playerNumbers.get(i)) {
counter++;
}
}
System.out.println("Number of matches in position: " + counter);
// if the position of match is not important
long matches = winningNumbers.stream()
.filter(playerNumbers::contains)
.count();
System.out.println("Number of matches: " + matches);
}
Number of matches in position: 2
Number of matches: 3

Counting the number of common elements in integer arrays located at different positions

For my assignment, I need to write a method that returns the number of cows (see definition below) found between 2 arrays. If the input arrays have a different number of elements, then the method should throw an IllegalArgumentException with an appropriate message.
A bull is a common number in int arrays found at the same position while a cow is a common number in int arrays found at different position. Note that if a number is already a bull, it cannot be considered as a cow.
For example, considering the following arrays:
int[] secret = {2, 0, 6, 9};
int[] guessOne = {9, 5, 6, 2};
int[] guessTwo = {2, 0, 6, 2};
int[] guessThree = {1, 2, 3, 4, 5, 6};
int[] guessFour = {1, 3, 4, 4, 0, 5};
1) getNumOfCows(secret, guessOne) returns 2
2) getNumOfCows(secret, guessTwo) returns 0
3) getNumOfCows(secret, guessThree) returns an exception
4) getNumOfCows(guessThree, guessFour) returns 2
My method seen below works perfectly for examples 1 and 3, but there is a problem with examples 2 and 4 such that getNumOfCows(secret, guessTwo) returns 1 instead of 0 because the element at secret[0] and guessTwo[3] is considered a cow. Could anybody help me fix my code?
// A method that gets the number of cows in a guess --- TO BE FIXED
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
// Initialize and declare a variable that acts as a counter
int numberOfCows = 0;
// Initialize and declare an array
int[] verified = new int[secretNumber.length];
if (guessedNumber.length == secretNumber.length) {
// Loop through all the elements of both arrays to see if there is any matching digit
for (int i = 0; i < guessedNumber.length; i++) {
// Check if the digits represent a bull
if (guessedNumber[i] == secretNumber[i]) {
verified[i] = 1;
}
}
for (int i = 0; i < guessedNumber.length; i++) {
// Continue to the next iteration if the digits represent a bull
if (verified[i] == 1) {
continue;
}
else {
for (int j = 0; j < secretNumber.length; j++) {
if (guessedNumber[i] == secretNumber[j] && i != j) {
// Update the variable
numberOfCows++;
verified[i] = 1;
}
}
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfCows;
}
First go through and mark all bulls using a separate array to make sure a position that is a bull also get counted as a cow
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
int max = secretNumber.length;
int cows = 0;
int[] checked = new int[max];
for (int i = 0; i < max; i++) {
if (secretNumber[i] == guessedNumber[i]) {
checked[i] = 1;
}
}
for (int i = 0; i < max; i++) {
if (checked[i] == 1) {
continue;
}
for (int j = 0; j < max; j++) {
if (secretNumber[i] == guessedNumber[j]) {
cows++;
checked[i] = 1;
}
}
}
return cows;
}
Now that this answer is accepted the original question can be voted to be closed as a duplicate
I am posting my answer from a duplicate question here and if this get approved then the other one can get closed as a duplicate.
The problem is that an element that is multiple times in at least one array will not be handled correctly.
A possible solution idea might be this one:
Create a cow list.
Iterate through both arrays and add every element that is in both arrays and has not been added yet. (note: complexity is n²)
Now that all possible cows are in the list, iterate through the array positions with the same index and if you find a bull, remove the number from the cow list.
Now the cow list contains only cows.
This solution might be a bit slower than your current one, but I think it's working properly.

Java program to find the duplicate values of an array of integer using simple loop

public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
for(int i= 0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if((array[i])==(array[j]) && (i != j)){
System.out.println("element occuring twice are:" + array[j]);
}
}
}
}
}
this program work fine but when i compile it, it print the values again and again i want to print the duplicate value once for example if 9 is present 5 times in array so it print 9 once and if 5 is present 6 times or more it simply print 5...and so on....this what i want to be done. but this program not behave like that so what am i missing here.
your help would be highly appreciated.
regards!
Sort the array so you can get all the like values together.
public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
Arrays.sort(array);
for (int a = 0; a < array.length-1; a++) {
boolean duplicate = false;
while (array[a+1] == array[a]) {
a++;
duplicate = true;
}
if (duplicate) System.out.println("Duplicate is " + array[a]);
}
}
}
The problem statement is not clear, but lets assume you can't sort (otherwise the problem greatly simplifies). Lets also assume the space complexity is constrained, and you can't keep a Map, etc, for counting the frequency.
You can use use lookbehind, but this unnecessarily increases the time complexity.
I think a reasonable approach is to reserve the value -1 to indicate that an array position has been processed. As you process the array, you update each active value with -1. For example, if the first element is 32, then you scan the array for any value 32, and replace with -1. The time complexity does not exceed O(n^2).
This leaves the awkcase case where -1 is an actual value. It would be required to do a O(n) scan for -1 prior to the main code.
If the array must be preserved, then clone it prior to processing. The O(n^2) loop is:
for (int i = 0; i < array.length - 1; i++) {
boolean multiple = false;
for (int j = i + 1; j < array.length && array[i] != -1; j++) {
if (array[i] == array[j]) {
multiple = true;
array[j] = -1;
}
}
if (multiple)
System.out.println("element occuring multiple times is:" + array[i]);
}
What you can do, is use a data structure that only contains unique values, Set. In this case we use a HashSet to store all the duplicates. Then you check if the Set contains your value at index i, if it does not then we loop through the array to try and find a duplicate. If the Set contains that number already, we know it's been found before and we skip the second for loop.
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
HashSet<Integer> duplicates = new HashSet<>();
for(int i= 0;i<array.length-1;i++)
{
if(!duplicates.contains(array[i]))
for(int j=i+1;j<array.length;j++)
{
if((array[i])==(array[j]) && (i != j)){
duplicates.add(array[i]);
break;
}
}
}
System.out.println(duplicates.toString());
Outputs
[3, 4, 5, 6, 7, 88, 8, 9]
I recommend using a Map to determine whether a value has been duplicated.
Values that have occurred more than once would be considered as duplicates.
P.S. For duplicates, using a set abstract data type would be ideal (HashSet would be the implementation of the ADT), since lookup times are O(1) since it uses a hashing algorithm to map values to array indexes. I am using a map here, since we already have a solution using a set. In essence, apart from the data structure used, the logic is almost identical.
For more information on the map data structure, click here.
Instead of writing nested loops, you can just write two for loops, resulting in a solution with linear time complexity.
public void printDuplicates(int[] array) {
Map<Integer, Integer> numberMap = new HashMap<>();
// Loop through array and mark occurring items
for (int i : array) {
// If key exists, it is a duplicate
if (numberMap.containsKey(i)) {
numberMap.put(i, numberMap.get(i) + 1);
} else {
numberMap.put(i, 1);
}
}
for (Integer key : numberMap.keySet()) {
// anything with more than one occurrence is a duplicate
if (numberMap.get(key) > 1) {
System.out.println(key + " is a reoccurring number that occurs " + numberMap.get(key) + " times");
}
}
}
Assuming that the code is added to ArrayTest class, you could all it like this.
public class ArrayTest {
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
ArrayTest test = new ArrayTest();
test.printDuplicates(array);
}
}
If you want to change the code above to look for numbers that reoccur exactly twice (not more than once), you can change the following code
if (numberMap.get(key) > 1) to if (numberMap.get(key) == 2)
Note: this solution takes O(n) memory, so if memory is an issue, Ian's solution above would be the right approach (using a nested loop).
// print duplicates
StringBuilder sb = new StringBuilder();
int[] arr = {1, 2, 3, 4, 5, 6, 7, 2, 3, 4};
int l = arr.length;
for (int i = 0; i < l; i++)
{
for (int j = i + 1; j < l; j++)
{
if (arr[i] == arr[j])
{
sb.append(arr[i] + " ");
}
}
}
System.out.println(sb);
Sort the array. Look at the one ahead to see if it is duplicate. Also look at one behind to see if this was already counted as duplicate (except when i == 0, do not look back).
import java.util.Arrays;
public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
Arrays.sort(array);
for(int i= 0;i<array.length-1;i++){
if((array[i])==(array[i+1]) && (i == 0 || (array[i]) != (array[i-1]))){
System.out.println("element occuring twice are:" + array[i]);
}
}
}
}
prints:
element occuring twice are:3
element occuring twice are:4
element occuring twice are:5
element occuring twice are:6
element occuring twice are:7
element occuring twice are:8
element occuring twice are:9
element occuring twice are:32
element occuring twice are:88

Finding missing number(s) from an array

Written this code, would like to get better approach using any algorithm to find missing numbers from an sorted or unsorted array. If its an unsorted array, i would sort and execute the following.
private static void identifyMissingValues(Integer[] ar) {
for(int i = 0; i < (ar.length - 1); i++) {
int next = ar[i + 1];
int current = ar[i];
if((next - current) > 1) {
System.out.println("Missing Value : " + (current + 1));
}
}
}
Any code faster or better than this, please suggest.
Any code faster or better than this, please suggest.
No there is no such thing - you cannot improve on an O(n) algorithm if every element must be visited.
Use BitSet instead of sorting.
int[] ar = {7, 2, 6, 8, 10, 4, 3, 2};
int min = IntStream.of(ar).min().getAsInt();
BitSet b = new BitSet();
for (int i : ar)
b.set(i - min);
int i = 0;
while ((i = b.nextClearBit(i + 1)) < b.length())
System.out.println(i + min);
result
5
9
Sorting the array would take O(n*log(n)).
You can do better if you add all the elements of the array to a HashSet (O(n)) running time, and then check for each number between 0 and ar.length - 1 (or whatever the relevant range is) whether the HashSet contains that number. This would take O(n) time.
Your approach is good, but I added something more for more than one numbers are missing..
eg : ar={1,2,4,6,10} // Sorted Array
private static void identifyMissingValues(Integer[] ar) {
for (int i = 0; i < (ar.length - 1); i++) {
int next = ar[i + 1];
int current = ar[i];
if ((next - current) > 1) {
for (int ind = 1; ind < next - current; ind++)
System.out.println("Missing Value : " + (current + ind));
}
}
}
Output is,
Missing Value : 3
Missing Value : 5
Missing Value : 7
Missing Value : 8
Missing Value : 9
Can I know the Input and Expected output number series ?
According to your code i feel the series should be a difference of 1,If i'm not wrong.
So you have an array of n elements which starts with an integer i and contains all integers from i to i+n is that right? Eg:
arr = [1,2,3,4,5]
So, the sum of all numbers in the array should be the sum of numbers from i to i+n.
Eg: sum(arr) = 1+2+3+4+5 = 15
The formula for the sum of numbers 1 to n is n(n+1)/2
So you can have a for loop as:
int counter = 0;
for(Integer i : integers)
counter += i
To get the sum of numbers in your array.
If your array starts at one, you check whether the counter variable equals n(n+1)/2, where n is the length of your array.
If your array doesn't start at one, for example arr = [78, 79, 80, 81] then you need to tweak this approach a little, but I'm sure you can figure it.
You can do:
Set<Integer> mySet = new TreeSet<Integer>(Arrays.asList(ar));
int min = mySet.first();
for (int i = 0; i < mySet.size(); i++) {
int number = min + i;
if (!mySet.contains(number)) {
System.out.println ("Missing: " + number);
i--;
}
}
Integer [] list = new Integer[]{1, 12, 85, 6, 10};
Integer previous = null;
Arrays.sort(list);
System.out.println(list);
for(int index = 0; index < list.length; index++){
if(previous == null){
previous = (Integer) list[index];
continue;
}
Integer next = previous + 1;
if(((Integer) list[index] - previous) > 1){
System.out.println("Missing value " + next);
index--;
}
previous = next;
}

Substitution in an Array List

I have to list out 10 unique numbers between 1 and 20, but before storing the numbers, the program should check whether the number is in the list or not. If the number is already in the list, it should generate a new number. Also, the amount of numbers replaced must be counted.
This is what I have so far:
public static void main(String[] args)
{
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
System.out.print("List: ");
for(int w = 0; w < arrayA.length; w++)
{
System.out.print(arrayA[w] + " ");
}
}
As you can see, there are two "3"s on the list, I have to output the same list but change one of the "3"s. Plus it has to be counted.
This is not hard to do, but what do you mean by change one of the threes?
You can add a boolean flag outside of your for loop that can tell if you've encountered a 3 or not and what the index of that 3 is.
Try something like this:
boolean changedThree = false;
int threeIndex = -1;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] == 3 && !changedThree){
arrayA[i] = 4;
threeIndex = i;
changedThree = true;
}
System.out.println(arrayA[i] + " ");
}
I don't know for sure if that captures the information you need, but hopefully can give you a push in the right direction. Let me know if you have questions.
EDIT
To avoid any duplicate values, I recommend you create an array list, and add the unique values to it. Then, you can use the ArrayList.contains() method to see if a value exists already. So, I would recommend changing your code to this:
ArrayList<int> usedCharacters = new ArrayList<int>();
int changedCounter = 0;
Random rand = new Random();
for(int i = 0; i < arrayA.length; i++){
if(!usedCharacters.contains(arrayA[i])){ // If we haven't used this number yet
usedCharacters.add(arrayA[i]);
} else{
// Generate a new number - make sure we aren't creating a duplicate
int temp = rand.nextInt(20) + 1;
while(usedCharacters.contains(temp)){
temp = rand.nextInt(20) + 1;
}
// Assign new variable, increment counter
arrayA[i] = temp;
changedCounter++;
}
}
If you're not familiar with the random.nextInt() method, read this.
so if I understand you correctly you have to save the arrayA, right?
If that is the case, you can just make a new array, targetArray where you can save to numbers to, and then check using a for-loop if you already added it, and if so you can generate a new, random number.
The result would look something like this:
public static void main(String[] args) {
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
int[] targetArray = new int[10];
int numbersReplaced = 0;
System.out.print("List: ");
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < targetArray.length; j++) {
if (arrayA[i] == targetArray[j]) {
targetArray[j] = (int)(Math.random() * 100);
numbersReplaced++;
} else {
targetArray[j] = arrayA[i];
}
}
}
System.out.println("Numbers replaced: " + numbersReplaced);
}
Hope that helped
You could use recursion to achieve your result.
This will keep looping until all values are unique
private void removeDoubles(int[] arr) {
for(int i = 0; i < arr.length; i++)
{
// iterate over the same list
for(int j = 0; j < arr.length; j++) {
// Now if both indexes are different, but the values are the same, you generate a new random and repeat the process
if(j != i && arr[i] == arr[j]) {
// Generate new random
arr[j] = random.nextInt(20);
// Repeat
removeDoubles(arr);
}
}
}
}
Note: This is the sort of question I prefer to give guidance answers rather than just paste in code.
You could walk the array backward looking at the preceding sublist. If it contain the current number you replace with a new one.
Get the sublist with something like Arrays.asList(array).subList(0, i) and then use .contains().
You logic for finding what number to add depends on lots of stuff, but at it simplest, you might need to walk the array once first to find the "available" numbers--and store them in a new list. Pull a new number from that list each time you need to replace.
EDIT: As suggested in the comments you can make use of Java Set here as well. See the Set docs.

Categories

Resources