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.
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
I am trying to shift all elements in my array to the left by 1, I am trying to remove the element 3 at index 0 from my array but the output I receive is completely different than what I expect. I don't understand why I receive this output.
The output I expect to receive is [2,2,3,0] I expect a zero on the last index because I shifted all elements to the left so there would be no value shifted to the last index. But I instead received [2,2,3,3]. I don't understand why a 3 is in the last index?
int [] nums = {3,2,2,3};
int length = nums.length;
for (int j = 1; j < length; j++) {
nums [j - 1] = nums [j];
}
return nums.length;
Try this, I just set the last one to 0:
int[] nums = {3,2,2,3};
int length = nums.length;
for (int j = 1; j < length; j++) {
nums [j - 1] = nums [j];
}
nums[nums.length - 1] = 0;
for (int number : nums) {
System.out.print(number);
}
I set the last number to 0 because you only changed the indices 0, 1 and 2 with your for-loop so that the last index, i.e. index 3, keeps the value 3.
So you get this: 2230.
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.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to draw a forloop of lines all spaced apart by 10 and I want the lines to be the length of the number of the int in the array. When I try to set their size as numbers[i] it gives me an array index out of bounds error the array is of size 50 and is filled with random numbers from 20-100.
private void drawPass(Graphics g) {
int space = 10;
for(int i = 0; i <= numbers.length; i++) {
g.drawLine(space, 1000, numbers[i], numbers[i]);
space += 10;
}
}
If your array is of length 50, then the last index you can access is 49 since the arrays are indexed starting at 0. In your current situation you are trying to access index 50 (which is what numbers.length is) which doesn't exist.
Change
i <= numbers.length;
to
i < numbers.length;
The change was from <= to just <. Now, instead of looping from 0-50, it goes from 0-49. To help visualize this
[5, 8, 3, 4, 9] // Random array of ints ( length = 5)
0 1 2 3 4 // Index of each position (last index = 4)