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 8 years ago.
Improve this question
I'm a relatively new java programmer and I've been tinkering around with this program for the better part of the day now and I'm still stuck; I was hoping that you could help me with this.
So the program is supposed to meet the following requirements:
Each new term in the Fibonacci
sequence is generated by adding the
previous two terms. By starting with 1
and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the
Fibonacci sequence whose values do not
exceed four million, find the sum of
the even-valued terms.
This is my code:
//Generates Fibonacci sequence
while (fibNum < 144)
{
int lastValue = (Integer) fibList.get(fibList.size()-1);
int secondToLastValue = (Integer) fibList.get(fibList.size()-2);
fibNum = secondToLastValue + lastValue;
if (fibNum < 144)
{
fibList.add(fibNum);
}
//Picks out the even numbers from limitFibList
for (int i = 0; i < fibList.size(); i++)
{
if ((Integer) fibList.get(i) % 2 == 0)
{
evenNumsFibList.add(fibList.get(i));
}
}
//Sums up the total value of the numbers in the evenNumsFibList
for (int i = 0; i < evenNumsFibList.size(); i++)
{
sum += (Integer) evenNumsFibList.get(i);
}
...and this is the output that I'm getting:
Fibonacci sequence list: [1, 2, 3]
Size of the Fibonacci list: 3
Even Numbers list: [2]
Total sum of even numbers: 2
Fibonacci sequence list: [1, 2, 3, 5]
Size of the Fibonacci list: 4
Even Numbers list: [2, 2]
Total sum of even numbers: 6
Fibonacci sequence list: [1, 2, 3, 5, 8]
Size of the Fibonacci list: 5
Even Numbers list: [2, 2, 2, 8]
Total sum of even numbers: 20
Fibonacci sequence list: [1, 2, 3, 5, 8, 13]
Size of the Fibonacci list: 6
Even Numbers list: [2, 2, 2, 8, 2, 8]
Total sum of even numbers: 44
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21]
Size of the Fibonacci list: 7
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8]
Total sum of even numbers: 78
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34]
Size of the Fibonacci list: 8
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34]
Total sum of even numbers: 156
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55]
Size of the Fibonacci list: 9
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 278
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Size of the Fibonacci list: 10
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 444
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Size of the Fibonacci list: 10
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 654
Obviously my while loop is contributing to my problems, but I don't know how to fix it.
Would greatly appreciate your help,
Haque
If you take a closer look at the numbers in the Fibonacci sequence that you actually need (only the even ones need to be summed), you will see a pattern:
0 1 1 2 3 5 8 13 21 34 55 89 144 ...
- O O E O O E O O E O O E
Notice that every 3rd number starting after 0 is even. Therefore, you can eliminate any checking for evenness if you calculate every third Fibonacci number. Looking again at the sequence, you can see that if k is the present even Fibonacci number you are looking at, and j is the one previous, the next even Fibonacci number n can be obtained by:
n = 4k + j
So in Java, you could try something like this:
int j = 0;
int k = 2;
int sum = j+k;
while (k < LIMIT) {
int tmp = 4*k + j;
sum = sum + tmp;
j = k;
k = tmp;
}
Looks like you are missing the close brackets on the while loop. So the other for's are running within it.
So:
while (fibNum < 144)
{
int lastValue = (Integer) fibList.get(fibList.size()-1);
int secondToLastValue = (Integer) fibList.get(fibList.size()-2);
fibNum = secondToLastValue + lastValue;
if (fibNum < 144)
{
fibList.add(fibNum);
}
}
//Picks out the even numbers from limitFibList
for (int i = 0; i < fibList.size(); i++)
{...
Am I missing something? Why do you need to create list? You just need a sum of even-valued numbers? Right? If I understand you correctly you can get your sum in 10 lines of code... I don't have Java IDE opend, so I'll give you Pythone code. If it is what you need I'll convert it into Java.
def fib(n=4000001): # write Fibonacci series up to n
r = 0
a, b = 0, 1
while b < n:
if not b%2 :
print(b, end=' ')
r += b
a, b = b, a+b
return r
OUTPUT:
2 8 34 144 610 2584 10946 46368 196418 832040 3524578
sum = 4613732
public class Euler002 {
int counter = 0;
public int getCounter () {
return counter;
}
public int getFibTotal () {
final int UPPER_LIMIT = 4000000;
int fib1 = 0;
int fib2 = 1;
int newFib = fib1 + fib2;
int total = 0;
while (newFib < UPPER_LIMIT) {
counter++;
fib1 = fib2;
fib2 = newFib;
newFib = fib1 + fib2;
if ((newFib % 2) == 0) {
total += newFib;
}
}
return total;
}
/**
* #param args
*/
public static void main(String[] args) {
Euler002 euler002 = new Euler002();
int total = euler002.getFibTotal();
System.out.println(" Counter = " + euler002.getCounter() + " And Fib Total is " + total);
}
}
The problem is here:
for (int i = 0; i < fibList.size(); i++)
{
if ((Integer) fibList.get(i) % 2 == 0)
{
evenNumsFibList.add(fibList.get(i)); <-- HERE
}
}
You're adppending a whole new list of all the even numbers to the end of the list you already have.
You need to delete everything in evenNumsFibList before calling this loop again, or modify the loop to only add even numbers that are not already in the list.
That's assuming your indentation is incorrect. If your indentation is actually how you want it, then you're simply missing a closing bracket on your while loop.
Related
Working through CodeSignal Arcade : https://app.codesignal.com/arcade/intro/level-5/XC9Q2DhRRKQrfLhb5,
You are given an array of integers representing coordinates of obstacles situated on a straight line.
Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.
Find the minimal length of the jump enough to avoid all the obstacles.
Example
For inputArray = [5, 3, 6, 7, 9], the output should be
solution(inputArray) = 4.
Check out the image below for better understanding:
https://i.stack.imgur.com/54Lty.png
Input/Output
[execution time limit] 3 seconds (java)
[input] array.integer inputArray
Non-empty array of positive integers.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 1000,
1 ≤ inputArray[i] ≤ 1000.
[output] integer
The desired length.
This is my code:
int solution(int[] a) {
Arrays.sort(a);
int ans = 0;
for (int jump = 2; jump <= 1000; jump++) {
int now = 0;
boolean flag = true;
while(now<=a[a.length-1]){
int next = now + jump;
if(Arrays.binarySearch(a, next)<0){
now = next;
} else{
flag = false;
break;
}
}
if(flag) {
ans = jump;
break;
}
}
return ans;
}
What I trying to do in my code is :
sort array to get largest element
increase "jump" until it can avoid all the elements in input array
These are some given test cases:
Input:
inputArray: [5, 3, 6, 7, 9]
Expected Output:
4
Input:
inputArray: [2, 3]
Expected Output:
4
Input:
inputArray: [1, 4, 10, 6, 2]
Expected Output:
7
Input:
inputArray: [1000, 999]
Expected Output:
6
Input:
inputArray: [19, 32, 11, 23]
Expected Output:
3
Input:
inputArray: [5, 8, 9, 13, 14]
Expected Output:
6
I passed all the test cases, but I get tripped up on one of the hidden tests when submitted.
I can't find counterexample and error in my code.
Thanks ahead of time for the help. I'm still quite new to coding and appreciate your time.
You are given a stack with n integers. You need to delete floor(n/2) elements from the bottom of the stack and print the remaining elements of the stack. The remaining elements should be printed in the order that they are inserted into the stack.
floor(3.5) will give the output as 3, greatest integer less than or equal to the input.
Input Format:
The first line of input is an integer n denoting the size of stack. The next line contains n space separated integers.
Output Format:
The remaining elements of the stack after removal of the required elements.
Example:
Stack(bottom -> top) = [1, 2, 3, 4, 5, 6]
Output: [4, 5, 6]
Stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Output: [6, 7, 8, 9, 10, 11]
Sample Input:
12
1 2 3 4 5 6 7 8 9 10 11 12
Sample Output:
[7, 8, 9, 10, 11, 12]
Sample input:
19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Sample Output:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Here my problem is my code passed test case 1 and test case 2 but in test case 3 where sample input is 19 there is should be printing as mentioned above output but my output came [11, 12, 13, 14, 15, 16, 17, 18, 19] its omitting 10th element and i dont know where is my error. So please help me in this
MY Code -
import java.util.*;
public class DeleteElement {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<>();
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while (n-- > 0)
stack.push(s.nextInt());
deleteFirstHalf(stack, stack.size(), 0);
System.out.println(stack);
}
static void deleteFirstHalf(Stack<Integer> stack, int n, int curr) {
if(stack.empty() || curr == n) {
return;
}
int x = stack.pop();
deleteFirstHalf(stack, n, curr+1);
if(curr<Math.floor(n/2)){
stack.push(x);
}
}
}
Note - Don't change the main() in my code.
I actually tried that with a Different Approach, where I created 2 different stacks temp and temp1, instead of recursively calling the function I had internal checks and printed the output at the end
static void deleteFirstHalf(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<Integer>();
Stack<Integer> temp1 = new Stack<Integer>();
int i = stack.size();
int dest = stack.size() / 2;
while (i-- > dest) {
int t = stack.pop();
temp.push(t);
}
while (!temp.empty()) {
int t = temp.pop();
// System.out.print(i + " size");
temp1.push(t);
}
System.out.print(temp1);
}
Your bug comes from the fact that you're supposed to delete the bottom floor(n/2) elements, but instead you're keeping the top floor(n/2) elements. The reason it works for some test cases is that when n is even, keeping the top n/2 elements is the same as deleting the bottom n/2 elements. When n is odd, the code should keep one extra element.
The solution is to change if (curr < Math.floor(n/2)) to if (curr < n/2 + n%2). For one, you can drop the Math.floor(), since integer division does floor division anyway. The key difference is the addition of n%2. n%2 evaluates to 0 when n is even, and 1 when n is odd. What this does is if n is odd, it will make the code keep one extra element. (in the case of the 3rd test case, it will keep 10 instead of deleting it) If n is even, n%2 evaluates to 0, so the algorithm behaves the same as before.
Instead of curr<Math.floor(n/2) try n-curr > Math.floor(n/2)
Instead of (curr<Math.floor(n/2)) try (curr < n-Math.floor(n/2))
So I have a random 15-puzzle, or any N-puzzle with even width, and I also have a random goal-state. That is, the blank tile and other tiles are also randomly placed.
I am able to check if the 15 puzzle is solvable with the standard goal state of having the tiles in order and blank in the bottom right, but randomizing the goal state seems to be more tricky than the standard 8 puzzle.
Example:
Start State
8 4 1 6
11 2 3 10
15 12 0 9
14 5 7 13
Goal State:
11 4 1 0
8 2 3 10
5 15 6 9
12 9 7 13
The rules for the standard 15-puzzle solvabilty are:
If the width is odd, then every solvable state has an even number of inversions.
If the width is even, then every solvable state has
An even number of inversions if the blank is on an odd numbered row
counting from the bottom;
An odd number of inversions if the blank is on an even numbered row
counting from the bottom;
I don't think different goal have any effect on solvability.
The simplest solution I can think of is to map numbers in the custom goal state to the numbers in the standard goal state. E.g: For the first row you treat 11 as if it was 0, 4-> 1, 1->2, 0->3 and so on.
The algorithm is the same as for standard puzzle, but you need a little change.
In general, the algorithm for reachability from start position S to goal position G is:
Calculate number of inversions in G - I(G)
Calculate number of inversions in S - I(S)
If:
width is odd and I(G) and I(S) have the same parity, G is reachable from S (in other words, S is solvable)
width is even:
Find the row number where blank is located in G - B(G)
Find the row number where blank is located in S - B(S)
If I(G)
is even and I(S) and abs(B(G) - B(S)) have the same parity, G is reachable from S
is odd and I(S) and abs(B(G) - B(S)) have different parity, G is reachable from S
In other cases G is unreachable from S.
Now let's see on your example. Represent a state as a list:
List<Integer> start = Arrays.asList(
8, 4, 1, 6,
11, 2, 3, 10,
15, 12, 0, 9,
14, 5, 7, 13);
List<Integer> goal = Arrays.asList(
11, 4, 1, 0,
8, 2, 3, 10,
5, 15, 6, 9,
12, 14, 7, 13); // in your example there's a second 9 instead of 14
A function, which will count number of inversions:
int inversions(List<Integer> numbers) {
int inversions = 0;
for (int i = 0; i < numbers.size(); i++) {
int n = numbers.get(i);
if (n <= 1) {
continue;
}
for (int j = i + 1; j < numbers.size(); j++) {
int m = numbers.get(j);
if (m > 0 && n > m) {
inversions++;
}
}
}
return inversions;
}
Finally, check the solvability:
boolean isSolvable(List<Integer> start, List<Integer> goal) {
int inversions = inversions(start);
int goalInversions = inversions(goal);
if (width % 2 == 0) {
int goalZeroRowIndex = goal.indexOf(0) / width;
int startZeroRowIndex = start.indexOf(0) / width;
// a little optimization is possible since we're only interested in parity
return (goalInversions % 2) == ((inversions + goalZeroRowIndex + startZeroRowIndex) % 2);
} else {
// for odd width just compare parity of inversions
return (inversions % 2) == (goalInversions % 2);
}
}
This function will work on both standard and random variations, regardless of 0 position.
For a given start and goal positions:
I(G) = 32
I(S) = 36
B(G) = 0
B(S) = 2
abs(B(G) - B(S)) = 2
I(G) is even and both I(S) and abs(B(G) - B(S)) have the same parity, so the puzzle is solvable. In fact, it is solvable in 31 moves:
12, 2, 11, 15, 2, 12, 9, 10, 6, 1, 4, 11, 15, 2, 12, 5, 14, 12, 5, 15, 2, 8, 11, 4, 3, 6, 10, 9, 6, 3, 1
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm sorry if my question is not very clear because i can't find any other way on how to explain it better.
I want to do something like this by using for loop:
First iteration : 0 , 1, 2, 3, 4,
Second iteration: 1, 2, 3, 4, 0
Third Iteration : 2, 3, 4, 0, 1
Fourth Itertaion : 3, 4, 0, 1, 2
Fifth iteration : 4, 0, 1, 2, 3
Final Iteration : 0, 1, 2, 3, 4
It will print value from 0 to 4 on the first iteration.
And then for the second iteration and the followings the pattern will continue as shown above.
Is it possible to do this using for loop in java?
What's wrong with
int iterations = 6;
for (int n = 0; n < iterations; n++) {
for (int i = 0; i < iterations - 1; i++) {
int value = (i + n) % (iterations - 1);
System.out.print(value + " ");
}
System.out.println();
}
Outputs
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
0 1 2 3 4
Without more information there's not much else to try. The modulo operator is your friend here, I suggest learning about it.
To rotate the array, start by saving the first element and then set every element from the first to the penultimate (that's the next to last) to the next value. Finally, set the last value to the first (that you saved). Something like,
private static void rotate(int[] arr) {
int first = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = first;
}
Then, clone the original array and iterate with a do while loop until your array equals its' original state. Something like,
int[] arr = { 0, 1, 2, 3, 4 };
int[] original = arr.clone();
do {
System.out.println(Arrays.toString(arr));
rotate(arr);
} while (!Arrays.equals(arr, original));
System.out.println(Arrays.toString(arr));
Which outputs (as requested)
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 0]
[2, 3, 4, 0, 1]
[3, 4, 0, 1, 2]
[4, 0, 1, 2, 3]
[0, 1, 2, 3, 4]
Also, in Java 8+, you might generate your array with
int[] arr = IntStream.rangeClosed(0, 4).toArray();
this is my first time asking a question on here so I apologize for any mistakes in terms of form.
I am working on an assignment for AP Computer Science which involves generating a listarray filled with random ints (within a certain range) and then processing them with methods that remove objects which either exceed or are less than a threshold determined earlier in the program. Here is an example of the code I wrote along with the preconditions provided by my teacher.
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return a new List of Integer that contains, in order, all the numbers in
* orig that are >= mid / 2
*/public static ArrayList<Integer> extractUpper(ArrayList<Integer> orig, int mid) {
ArrayList<Integer> myArray = new ArrayList<Integer>();
for(Integer a: orig) {
if (a >= mid/2)
myArray.add(a);
}
return myArray;
}
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return none PostCondition: all numbers less than mid / 2 have been
* removed from orig
*/
public static void deleteUpper(ArrayList<Integer> orig, int mid) {
for(int j = 0; j < orig.size(); j++) {
if (orig.get(j) >= (mid/2))
orig.remove(j);
}
}
To me, this seems like it should work fine, but when I run this:
ic static void main(String[] args) {
//a.
int listLen = 10;
int listMax = 20;
System.out.println("listLen equals " + listLen + " and listMax equals " + listMax);
System.out.println();
//b.
System.out.println("Generating a fixed-length ArrayList of length " + listLen + " with all values >= 0 and < " + listMax);
ArrayList<Integer> Array1 = Main.buildFixedList(listLen, listMax);
System.out.println(Array1);
//c.
System.out.print("The numbers in this ArrayList >= " + listMax/2 + " are: ");
ArrayList<Integer> Array2 = Main.extractUpper(Array1, listMax);
System.out.println(Array2);
//d.
System.out.print("After deleting numbers > " + listMax/2 + " the modified list is: ");
Main.deleteUpper(Array1, listMax);
System.out.println(Array1);
//e.
System.out.print("After deletion, the numbers in the List >= " + listMax/2 + " are: ");
ArrayList<Integer> Array3 = Main.extractUpper(Array1, listMax);
System.out.println(Array3);
//f.
System.out.println();
My output seems to ignore certain numbers, some more frequently than others.
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[14, 16, 12, 9, 8, 11, 14, 16, 1]
The numbers in this ArrayList >= 10 are: [14, 16, 12, 11, 14, 16]
After deleting numbers > 10 the modified list is: [16, 9, 8, 14, 1]
After deletion, the numbers in the List >= 10 are: [16, 14]
The >=10 and <10 methods work occasionally, but I figure it's more of a crap-shoot right now. In this particular example the >=10 method worked but the <10 did not. I am at a loss as to what is wrong with my code.
EDIT:
Thank you for all the replies, I appreciate the help. I have edited both the extractUpper and deleteUpper methods and am getting an even higher rate of success, but the code just seems to ignore some numbers. Here's the code:
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return a new List of Integer that contains, in order, all the numbers in
* orig that are >= mid / 2
*/public static ArrayList<Integer> extractUpper(ArrayList<Integer> orig, int mid) {
ArrayList<Integer> myArray = new ArrayList<Integer>();
for (int i = 0; i < orig.size(); i++){
if(orig.get(i) >= mid/2) {
myArray.add(orig.get(i));
}
}
return myArray;
}
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return none PostCondition: all numbers less than mid / 2 have been
* removed from orig
*/
public static void deleteUpper(ArrayList<Integer> orig, int mid) {
for ( int i = orig.size()-1; i >= 0; i--){
if (i < orig.size()) {
if(orig.get(i) >= mid/2) {
orig.remove(i);
i++;
}
}
else
i--;
}
}
Here are a few outputs directly from the program:
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[4, 15, 8, 11, 18, 16, 7, 3, 6]
The numbers in this ArrayList >= 10 are: [15, 11, 18, 16]
After deleting numbers > 10 the modified list is: [4, 8, 7, 3, 6]
After deletion, the numbers in the List >= 10 are: []
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[6, 3, 9, 16, 4, 4, 17, 8, 4]
The numbers in this ArrayList >= 10 are: []
After deleting numbers > 10 the modified list is: [6, 3, 9, 4, 4, 8, 4]
After deletion, the numbers in the List >= 10 are: []
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[4, 5, 0, 4, 12, 12, 1, 12, 10]
The numbers in this ArrayList >= 10 are: [12, 12, 12, 10]
After deleting numbers > 10 the modified list is: [4, 5, 0, 4, 1, 12]
After deletion, the numbers in the List >= 10 are: [12]
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[15, 16, 2, 8, 1, 7, 3, 0, 15]
The numbers in this ArrayList >= 10 are: [12]
After deleting numbers > 10 the modified list is: [2, 8, 1, 7, 3, 0]
After deletion, the numbers in the List >= 10 are: [12]
Your problem is in the function deleteUpper
You should iterate in reverse order the collection to be able to remove item without impacting the original index of the collection
The problem is in the deleteUpper method.
When you delete an item from an List, the indexes in that List change - if you remove item 3, the item that was previously accesible at index 4 now becomes number 3.
In your implementation you always increase the index pointer, regardless if the deletion happened or not. This means that if two consecutive items meet the deletion criterion, only the first one will be removed.
Use an Iterator instead:
Iterator<Integer> i = orig.iterator();
while (i.hasNext()) {
if (i.next() >= mid) {
i.remove();
}
}
If you don't want to use an Iterator:
for (int i=0; i<orig.size(); ) {
if (orig.get(i) >= mid) {
orig.remove(i);
}
else {
i++;
}
}