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];
}
}
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.
I am trying to print the picture below using nested loops (I should use for & while loops):
**
****
******
********
Starts with 5 spaces, decreasing by 2 each line.
Starts with 2 stars, increasing by 2 each line.
Ends at 4 lines.
My code works on the first line, but it does not print the stars on the remaining 3 lines. Can someone see what the error may be? Please do not give the answer, I just need help understanding the logical error!
int m = 6;
int n = 0;
for(int l = 1; l < 5; l++){
while(m > 0){
System.out.print(" ");
m--;
}
while(n < (2*l)){
System.out.print("*");
n++;
}
System.out.println();
m = 5 - (2*l);
n = n + 2;
}
The error is that you don't reset the n variable each loop. You add 2 to it after the first loop at which point is is already larger than 2 * l so no more stars will be printed.
It would be more sensible to structure it as:
for (int l = 0; l < 4; l ++) {
for (int i = 0; i < 5 - 2l; i++)
System.out.print(" ");
for (int i = 0; i < 2 + 2l; i++)
System.out.print("*");
System.out.println();
}
Hint:
look at m=5 - (2×l);
as soon as l=3
the result will be negativ and the first while-loop wont be executed
Just like you add two to n, you have to remove 2 from m. If I understand quite well, m is your number of spaces and n is your number of stars so if you add two stars; n+2 then you have to remove the space too so: m - 2 since the two added stars occupy that space.
m = m - 2;
n = n + 2;
Edit: you also have to change the while loop where the n is edited, in order not to change the n:
int temp = n;
while(temp > (2*l)){
System.out.print("*");
temp++;
}
Use nested for loops the outer loop moves down the rows and the inner loop moves along the columns. Each pass through the inner loop should check whether ro place an empty space or an asterisk. This can be done with an if statement use the integer variables in the for loops to determine when to place a space or an asterisk. The algorithm for this will vary depending on the shape you want.
Alternatively the use of a doubly indexed array might be interesting here. More complext but maybe something to look at if you need to use a while loop. It might be possible to use for loops to fill a doubly indexed char array with either a " " or a "*" and then simply print out ghe contents of the array while setting the value to null after printing and checking to see if the array is empty or not.
Maybe some of this was helpful. Happy coding.
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
}
This question already has answers here:
post increment operator java
(3 answers)
Closed 8 years ago.
what would be the output of
1).
int j=0;
for (int i=0; i<100; i++) j=j++;
System.out.println(j);
I thought j=j++; will be equal to
int j2 = j;
j = j+1;
so I was expecting the out put would be 99. but when I compiled on eclipse output was 0.
2). and I could not understand what is the logic behind
((int)(char)(byte) -1)
When ran it on eclipse I got output as 65535.
j=j++;
is functionally equal to
int xxx = j;
j++;
j = xxx;
So the value of j stays the same. (Because the right side is evaluated first, including the increment, then the result is assigned to j)
As for ((int)(char)(byte) -1), a char is 16bit in size and unsigned, so the bit pattern of -1 results in 65535.
This is because the ++ works as follows:
a = 0;
a = a++; // a will get the assignment of the current value of a before the increment occurs so a = 0 in here
However, in the next case here:
a = 0;
a = ++a; // a will get the assignment of the incremented value of a so a = 1 in here