How to find missing numbers in an integer array in Java? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I couldn't find a solution for this in Java. I need to write code that will take an integer n, and an array of integers that has numbers up to n(some may be missing), and the method will print out which numbers are missing
ex: {2; 3; 5; 1; 2; 3} should print out 4, 6
Edit: Here is what I got from the comments suggestion, but it doesn't seem to work. What did I do wrong?
public static void findMissingNum(int n, int[]a) {
boolean A[] = new boolean[n];
for(int i = 0; i < a.length; i++) {
A[a[i]] = true;
}
for(int j = 0; j < A.length; j++) {
if (A[j] = false) {System.out.print(A[j]);}
}
}

I've seen this used as a homework or quiz problem before, the question is begging you to use a hash table. Create an empty Boolean array of size n and for each number in the list set array[num] to True. Loop over the new array, and record all the instances of False, you know ahead of time how many there should be.

The following ought to work:
public void find() {
Scanner s = new Scanner(System.in);
int[] nums = {2, 3, 5, 1, 2, 3};
int n = s.nextInt();
boolean[] included = new boolean[n+1];
for(int i = 0; i < nums.length; i++) included[nums[i]] = true;
for(int z = 0; z < included.length; z++) {
if(included[z] == false) System.out.print(z+ ",");
}
}
This will print out all missing numbers including n (if it is missing). If n is not included then do new boolean[n]
The way it works is by first using Scanner to read in your int n. It has two arrays, an int array which has your numbers, and a boolean array which serves as a set of flags. The boolean array is initalized to the size of n. Then it loops through the nums array and sees what numbers are included in the array. If the number is included, its element in the boolean arary is flagged as true. Finally, it loops through the flags/boolean array, if the element at that flag is true, do nothing since its already there, otherwise if its false (meaning the # wasn't included) then print it.

Try to implement this solution in Java:
Create second array A = [0,..,n] of booleans. Initialize it with false values.
Iterate through input array: for i = 0 to length(inputArray): A[inputArray[i]] := true.
Check which indexes in array have value false, those are the values that You want to return.

List< Integer > list = Arrays.asList(yourArray);
Then you can just create an array from 1 up to n with all numbers in order, and iterate through its elements checking for each one if your list contains it or not, adding it to another missingValues list if not.

Related

Count repetitions in array in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I know that similar questions have been asked and I have researched
many websites. I have tried to use some of the answers but my code is
still not working.
I am going through a previous assignment to help build my knowledge
of Java. Please forgive any errors in my code, I am still learning
Java.
Here is my question:
Implement a method count which, given an array of integer elements, returns another array containing the number of occurrences of each integer {0, ..., r} in the input array, where r is an integer to show the upper boundary of the integers that you need to count.
The returned array of counts will be of size r + 1, where the element at each index i corresponds to the number of occurrences of integer i (with i in {0, ..., r}).
Elements in the input array outside of the integer range from 0 to r can be ignored.
For example, given the input [0, 8, 1, 3, 1, 3, 10, 3] with r is 4, the output should be [1, 2, 0, 3, 0].
If the input array is null or of length 0, this will return null.
Space requirements: Method count should only use additional space for the count array.
Time requirements: The counts should be calculated in a single pass through the input array.
Here is what I've done so far, it doesn't meet the requirements so I need help in order to find the right solution:
public static int[] count(int[] arr, int r) {
int[] count = new int[r + 1];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < r; j++) {
if (arr[i] == j) {
count[i]++;
}
}
}
return count;
}
You are really close, but seems maybe a small bit is wrong.
int[] count = new int[r + 1];
for (int i = 0; i < arr.length; i++) {
if( arr[i] <= r) {
count[arr[i]]++;
}
}
I think the above will work, if you think about it, each element of arr corresponds to an index in count as long as that index is within {0...r}, so we check that the value is within that range, then we increment the integer at that index within count.

Changing Array to ArrayList [duplicate]

This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}
There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.
Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case
An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...

How to write a function named isMeera that returns 1 if its array argument is a Meera array. Otherwise, it returns 0 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
A Meera array is defined to be an array that contains at least one odd number and begins and ends with the same number of even numbers.
So {4, 8, 6, 3, 2, 9, 8,11, 8, 13, 12, 12, 6} is a Meera array because it begins with three even numbers and ends with three even numbers and it contains at least one odd number.
The array {2, 4, 6, 8, 6} is not a Meera array because it does not contain an odd number.
The array {2, 8, 7, 10, -4, 6} is not a Meera array because it begins with two even numbers but ends with three even numbers.
Here is my try but could not get the result. Please help me ! Thank in advance!
public static int isMeera(int [] a){
boolean hasOdd = false;
int firstEven = 0;
int lastEven = 0;
boolean firstCountEnd = false;
boolean lastCountEnd = false;
for(int i = 0; i<a.length; i++){
if (a[i]%2 == 1)
{
hasOdd = true;
break;
}
}
for (int j = 0; j<a.length; j++){
if(a[(a.length - 1) - j] % 2 == 1){
firstCountEnd = true;
if ((!firstCountEnd) && (a[j]%2==0)){
firstEven ++;
}
}
if(a[(a.length - 1) - j] % 2 == 1){
lastCountEnd = true;
if ((!lastCountEnd) && (a[j]%2==0)){
lastEven ++;
}
}
}
if (hasOdd && firstEven == lastEven)
return 1;
return 0;
}
Here's a working answer!
public static bool IsMirra(int[] l1)
{
return((l1.Select(l=>l%(1<<1)==(1>>1)?'l':'1').TakeWhile(l=>(l^(((1<<1)+(1<<(1^1))<<((1<<1)<<1))+(1<<(1^1))))!=(l^l)).Count()-l1.Select(l=>l%(1<<1)==(1>>1)?'l':'1').Reverse().TakeWhile(l=>(l^(((1<<1)+(1<<(1^1))<<((1<<1)<<1))+(1<<(1^1))))!=(l^l)).Count())==(1^1))&&(l1.Select(l=>l%(1<<1)==(1>>1)?'l':'1').Any(l=>(l^(((1<<1)+(1<<(1^1))<<((1<<1)<<1))+(1<<(1^1))))==(l^l)));
}
If you actually want a legible answer as opposed to just a functional one, I'd be happy to help once you put in the effort and take a stab at it yourself.
Edit
Okay, since you actually showed some effort and posted what you had, here are some tips:
Check if there's at least one odd number in the array.
Add a piece of code that takes your array and counts how many even numbers the array begins with. Store that as a variable.
Now add a piece of code that takes your array and counts how many even numbers the array ends with. Store that as a variable.
I think your code for #1 works - it looks okay. I would recommend getting rid of the second loop you have and breaking it into two - one starting at the beginning of the array and counting forwards, one starting at the end and counting backwards. You can actually skip both of these loops if there is no odd number because you already know it's not a "mirra" array.
There are more optimizations you could do to reduce the number of elements of the array you need to access, but for now I'd focus on writing a legible, correct solution and not necessarily the most optimized solution possible.
By the way, all of that is essentially what my very obfuscated code did - it counted the number of leading even numbers of the array, it counted the number of leading even numbers of a reversed copy of the array (i.e. the number of terminal even numbers), and it checked for the existence of at least one odd number.
Finally it works successfully !
public static int isMeera(int [] a){
boolean hasOdd = false;
int firstEven = 0;
int lastEven = 0;
boolean firstCountEnd = false;
boolean lastCountEnd = false;
for(int i = 0; i<a.length; i++){
if (a[i]%2 == 1)
{
hasOdd = true;
break;
}
}
if (!hasOdd)
return 0;
for (int j = 0; j<a.length; j++){
if(a[j]%2==1)
firstCountEnd=true;
if(!firstCountEnd && a[j]%2==0)
firstEven++;
if(a[(a.length-1)-j]%2==1)
lastCountEnd=true;
if(!lastCountEnd && a[(a.length-1)-j]%2==0)
lastEven++;
}
//System.out.println(firstEven +" " +lastEven);
if (hasOdd && firstEven == lastEven)
return 1;
return 0;
}

What is wrong with my Java solution to Codility MissingInteger? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to solve the codility MissingInteger problem link:
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.
For example, given:
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2
the function should return 5.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
My solution is:
class Solution {
TreeMap<Integer,Object> all = new TreeMap<Integer,Object>();
public int solution(int[] A) {
for(int i=0; i<A.length; i++)
all.put(i+1,new Object());
for(int i=0; i<A.length; i++)
if(all.containsKey(A[i]))
all.remove(A[i]);
Iterator notOccur = all.keySet().iterator();
if(notOccur.hasNext())
return (int)notOccur.next();
return 1;
}
}
The test result is:
Can anyone explain me why I got this two wrong answers? Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1?
Here is my answer, got 100/100.
import java.util.HashSet;
class Solution {
public int solution(int[] A) {
int num = 1;
HashSet<Integer> hset = new HashSet<Integer>();
for (int i = 0 ; i < A.length; i++) {
hset.add(A[i]);
}
while (hset.contains(num)) {
num++;
}
return num;
}
}
returns the minimal positive integer that does not occur in A.
So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.
I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the indexes of the given array, and then removing keys based on the values it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.
So, for example, if you iterate from 1 to Integer.MAX_VALUE, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at O(n).
I have done the answer inspired by the answer of Denes but a simpler one.
int counter[] = new int[A.length];
// Count the items, only the positive numbers
for (int i = 0; i < A.length; i++)
if (A[i] > 0 && A[i] <= A.length)
counter[A[i] - 1]++;
// Return the first number that has count 0
for (int i = 0; i < counter.length; i++)
if (counter[i] == 0)
return i + 1;
// If no number has count 0, then that means all number in the sequence
// appears so the next number not appearing is in next number after the
// sequence.
return A.length + 1;
returns the minimal positive integer that does not occur in A
The key here is that zero is not included in the above (as it is not positive integer). So the function should never return 0. I believe this covers both of your failed cases above.
edit: due to the fact that question has been changed since this was written this answer isn't really relevant anymore
Very little wrong.
Just the last line
return 1;
should read
return A.length + 1;
because at this point you've found & removed ALL KEYS from 1 to A.length since you have array entries matching each of them. The test demands that in this situation you must return the next integer above the greatest value found in array A.
All other eventualities (e.g. negative entries, missing 1, missing number between 1 and A.length) are covered by returning the first unremoved key found under iteration. Iteration here is done by "natural ordering", i.e. 1 .. max, by default for a TreeMap. The first unremoved key will therefore be the smallest missing integer.
This change should make the 2 incorrect tests okay again. So 50/50 for correctness.
Efficiency, of course, is another matter and one that carries another 50 points.
Your use of the TreeMap data structure here brings a time penalty when evaluating the test results. Simpler data structures (that essentially use your algorithm) would be faster.
This more primitive algorithm avoids sorting and copies all entries > 1 onto a new array of length 100001 so that index x holds value x. It actually runs faster than Serdar's code with medium and large input arrays.
public int solution(int[] A)
{
int i = 0,
count = 0,
N = A.length;
int[] B = new int[100001]; // Initially all entries are zero
for (i = 0; i < N; i++) // Copy all entries > 0 into array B ...
{
if (A[i] > 0 && A[i] < 100001)
{
B[A[i]] = A[i]; // ... putting value x at index x in B ...
count++; // ... and keep a count of positives
}
}
for (i = 1; i < count + 1; i++) // Find first empty element in B
{
if (B[i] == 0)
{
return i; // Index of empty element = missing int
}
}
// No unfilled B elements above index 0 ?
return count + 1; // => return int above highest filled element
}

Adding elements to array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
First off apologies if this is a simple question, but I am very stuck with it.
I need to create an array with a total number of elements, there is 14. I want to add each of the 14 elements to the array and was recommended doing this with a loop as I will be doing more tasks like this but with much more elements. I have tried this code so far but am having no luck;
int [] deviceID;
for(int i = 292; i <= 305; i++)
{
deviceID[i];
}
but I get the exception insert "AssignmentOperator Expression" to complete Expression.
So then I changed the line to
deviceID = deviceID[i];
Now I get a Type Mismatch: cannot convert from int to int[]
just to be clear I want slot 0 of the array have the value 292, slot 1 have 293........slot 14 have 305
Can anyone help me on this? What I thought would be basic and easy is turning into a bit of a nightmare for me.
You need to initialize array int[] deviceId = new int[20];
I guess you want to add 292 to 305 in array.
int [] deviceID= new int[14];//total element 14 (index 0 to 13)
int j=0;//counter which provides index during loop
for(int i = 292; i <= 305; i++)
{
if(j<deviceID.length)//chech whether j<14 as we want to add upto index 13
deviceID[j++]=i;//store i to the array at index j
//increments j to provide next index
}
I suggest you to read about Arrays from Java Doc it will clear all your dobts and bring some extra energy in you to start coding again.
I don't understand what you want to do, but if you want to have values from 292 to 305 in an array you should do:
int [] deviceID = new int[305];
for(int i = 292; i <= 305; i++)
{
deviceID[i] = i;
}
But it's really weird. What is your purpose ?
If you're trying to fill your integer array deviceID with those values of i, you'll need to first make sure the array is big enough, and then simply fill the array. Your problem was from trying to set your entire array equal to a single integer from one index (hence the type mismatch error).
int[] deviceID = new int[necessarySize]; // Creates an array with size "necessarySize"
int counter = 0;
for(int i = 292; i <= 305; i++)
{
deviceID[counter] = i; // Fills the array at index "counter" with value "i"
counter++;
}
If this is your entire array, then you'd only need (305-292)+1 = 14 spaces in your array.
DO THIS
int[] deviceId = new int[14]; //this creates a new array with size 14
int j=0; // for array index
for(int i = 292; i <= 305; i++)
{
deviceID[j] = i; //this inserts value of i at array position j
j++; //this keeps on adding 1 to previous value
}
You need to instantiate the array.
int[] deviceId = new int[sizeOfArray];
Where sizeOfarray, is an integer value indicating the size of the array.
Then to assign the position, you must use
deviceId[index] = value;
deviceID[i] just gets the i'th element in deviceID and does nothing with it.
deviceID = deviceID[i] is trying to assign an int to an object declared as a list, hence your error.
What you want to do is:
List<int> deviceID = new List<int>()
for(int i = 292; i <= 305; i++)
{
deviceID.add(i);
}
This should give you a list with only the numbers 292-305 in it

Categories