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 days ago.
Improve this question
Im supposed to count how many numbers are duplicated in a array and have a issue when numbers are duplicated more than 2 times etc 1 1 1 is supposed to count as 1 but is counted as 3 instead
public static int dublleter(int[] input) {
int input2[] = { 1, 2, 3, 1, 1, 4, 5, 2 };
int count = 0;
for (int i = 0; i < input2.length; i++) {
for (int j = i + 1; j < input2.length; j++) {
if (input2[i] == input2[j]) {
count++;
}
}
}
return count;
}
Tried implimenting if terms but it hasnt worked out good
I would suggest using a map. As you iterate over the array, if the int isn't in the map, add it to the map with a value of 1. Otherwise, increment it. When you're done, count how many keys have values larger than 1 associated with them.
Sort of a psuedocode approach:
my_map = new map
for x in array
if x is a key in my_map
my_map[x] += 1
else
my_map[x] = 1
end if
end for
Now your map might look like:
{
1 => 3,
2 => 2,
3 => 1,
4 => 1,
5 => 1
}
If we select all of the keys that map to a value greater than 1, we get [1, 2].
With your approach, when you evaluate 1, you are going to hit 1 two more times, so count will be 2. Looking at 2 count will be incremented once to 3. Evaluating 1 a second time, count will again increment to 4.
You could also sort the array first, then check for duplicates, advancing forward past those repeated entries so you don't count repetitions of the same number more than once.
U can use map as u will set the
key as the number and the value of it will be the number of occurrence of that
key and for the not occurred numbers like 4 it will be one as it appears one time
so U will give initial value to count the variable U created in your code as 1 or put 1 direct.
Map<Integer, Integer> map = new HashMap<>();
for (Integer x : input2) {
if (map.get(x) == null)
map.put(x, count);
else
map.put(x, map.get(x).intValue() + 1);
}
Related
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 11 months ago.
Improve this question
Hi Im searching a fast dynamic programming / formula solution. For following algorithm, example:
init := 1
elements := 4
steps := 3
step 1. [1,1,1,1] init is placed in each index
step 2. [1,2,3] index i is calculated by sum of former step index 0 until inclusive step 1 index i, arraysize get's decremented by one.
step 3. [1,3] Same procedere like step 2 but using step 2 as base.
final step solution := 4 final step is summing up last stepelements.
Is there a faster way than summing up manually?
Sample Code:
long calc(int init,int elements,int steps){
int[] dp1 = new int[elements-1];
Arrays.fill(dp1, init);
int[] dp2 = new int[elements-1];
for(int i = 0; i < steps-1; i++){
for(int j = 0,cur = 0; j < elements-i-1; j++){
dp2[j] = cur = cur + dp1[j];
}
System.arraycopy(dp2,0,dp1,0,elements-i-1);
Arrays.fill(dp2, 0);
}
return Arrays.stream(Arrays.copyOf(dp1,elements-steps+1)).sum();
}
You're doing a lot of copying and filling where none is necessary. Try it like this.
static long myCalc(int init, int elements, int steps) {
if (steps > elements+1) {
System.out.println("Steps too large for # of elements");
return -1;
}
int[] dp1 = new int[elements - 1];
Arrays.fill(dp1, init);
int len = dp1.length;
for (int j = 0; j < steps - 1; j++) {
for (int i = 1; i < len; i++) {
dp1[i] = dp1[i - 1] + dp1[i];
}
len--;
}
return Arrays.stream(dp1).limit(len+1).sum();
}
Added improvement. For each step, one less value is added. So adjust the for loop iterations to accommodate.
You might want to look at the Arrays.parallelPrefix method. From the java doc:
Cumulates, in parallel, each element of the given array in place, using the supplied function. For example if the array initially holds [2, 1, 0, 3] and the operation performs addition, then upon return the array holds [2, 3, 3, 6]. Parallel prefix computation is usually more efficient than sequential loops for large arrays.
So something like below might be what you are looking for :
long calc(int init,int elements,int steps){
int[] arr = new int[elements];
Arrays.fill(arr,init);
int[] curr = arr;
for (int i = 1; i < steps; i++){
Arrays.parallelPrefix(curr, Integer::sum);
curr = Arrays.copyOf(curr,curr.length-1);
System.out.println(Arrays.toString(curr)); // just to check the sub steps, remove if I get the discription of the steps right
}
return Arrays.stream(curr).sum();
}
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 2 years ago.
Improve this question
what I attend to do is when the array(from 0 to n-1) is given, to sum the array values with the index minus multiple of 3 start from the end.
for example, when 7 arrays are given, I want to sum a[0] a[2] a[3] a[5] a[6].
below is error part of the code I programmed.
int j = 0;
for(int i=0; i<n; i++){
j = i*3;
if(i!=n-j)
r += array[i];
}
my code can't read the condition and just sum all the array values.
I don't know why. can someone help me ?
Let's debug!
first time through the loop:
i = 0
j = i * 3 soo... 0
if (0 != 7 - 0) ... - it's not, of course, so i = 0 qualifies and is added.
next loop:
i = 1
j = 3
if (1 != 7 - 3) ... - it's not, of course, so i = 1 qualifies and is added.
Which you did not want.
Given that this is homework, this should be enough for you to take another step and figure out what you SHOULD be doing here. I will give some tips:
You can loop, counting backwards, just as well. You'd have to use i-- of course (decrement i by 1 every time), and you'd use int i = n or perhaps int i = n - 1 as initializing expression in your for loop.
That whole 'is it a 3rd factor from the top' part cannot be calculated using i at all, you'd need something separate for this. You can declare variables outside (you already did that, int j = 0, but you're not looking for 0 so much as 'the first index from the top I do not want'. Then you can use if to check if it is that index. If so, you don't want to add that number to your sum AND you want to update your j.
For tasks like that the modulo operator is usually your friend.
I tried it like this and it works:
int r = 0;
int[] array = new int[7];
for(int i = array.length; i >= 0; i--){
int numberOfIteration = array.length - i;
if(numberOfIteration % 3 > 0){
System.out.println("Add array[" + i + "]");
r += array[i];
}
}
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.
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
}
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 8 years ago.
Improve this question
I would like to for-loop a set of numbers and change their positions in each line. It reads a series of integers (at most 10) until a non-integer has been inputted from the keyboard. My expected result is something like this:
>> 4 0 3 4 2 q
4 0 3 4 2
0 3 4 2 4
3 4 2 4 0
4 2 4 0 3
2 4 0 3 4
Can anybody teach me how to deal with it? Thanks in advance.
With some knowledge of modular arithmetic you can fold an array around into a circle. Observe that the starting point of each index shifts to the right by one place from the starting point of the previous row. So you do your loop like this:
n := length of the array
for i = 0 to n-1 (assuming the array is zero-based)
j := i
do loop
print(array[j])
j := j + 1
j := j%n
until j = i
end for
This is a language independent pseudo-code. Adapt it to whatever language your're coding in.
Here is a method to shift the numbers like you want. I took the liberty of commenting it to give you a better understanding of what's going on.
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
The following snippet should change the contents of the array to be {0, 3, 4, 2, 4}
shift(new int[] {4, 0, 3, 4, 2})
Here is a complete, runnable class file.
import java.util.Arrays;
public class Shift {
public static void main(String[] args) {
int[] numbers = new int[] {4, 0, 3, 4, 2};
shift(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
}
EDIT:
To use an ArrayList called list, you can use the following snippet:
list.add(list.remove(0));
This is because ArrayList.remove(int) will return the object removed from the array, so we can just add it on to the end.