what is wrong with this code in projectEuler 10? [closed] - java

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 7 years ago.
Improve this question
i wrote this code for project Euler problem 10 . but in line 24 it has an error. how to fix it?
public static void main(String[] args) {
int i;
int b = 2000;
List<Integer> notPrime = new ArrayList<Integer>();
notPrime.add(2);
notPrime.add(3);
notPrime.add(5);
notPrime.add(7);
for (i = 2; i < b; i++) {
if (i % 2 != 0 && i % 3 != 0 && i % 5 != 0 && i % 7 != 0) {
notPrime.add(i);
}
}
for(int primesNum:notPrime){
int dd = (int) Math.pow(primesNum, 2);
int indexofdd = Arrays.asList(notPrime).indexOf(dd);
//here is the error
notPrime.remove(indexofdd);
}
int summy = notPrime.stream().mapToInt(Integer::intValue).sum();
System.out.println(summy);
}

The type of Arrays.asList(notPrime) is List<List<Integer>>, meaning that Arrays.asList(notPrime).indexOf(<some int>) is always going to be -1 (not found), because a List<List<Integer>> cannot contain an Integer.
Hence the call to List.remove will fail, since as the Javadoc states:
Throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()).
You can simply write:
notPrime.remove(Integer.valueOf(dd));
(No need for separate indexOf call)
You need the Integer.valueOf in order to ensure that List.remove(Object) is invoked, rather than List.remove(int): the latter removes the element at the given index, whereas the former removes the list element with the given value.
However, the logic of this code looks more generally faulty.

Related

How to deal with IndexOutOfBounds error in arrays in such a case? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last month.
I need to create a method for my OOP lab, the details are as the following:
A ThreeWayLamp class models the behavior of a lamp that uses a
three-way bulb. These bulbs have four possible states: off, low light, medium
light, and high light. Each time the switch is activated, the bulb goes to the next
state (from high, the next state is off, from off to low etc). The ThreeWayLamp
class has a single method called switch() which takes a single int parameter
indicating how many times the switch is activated. (you need to throw an
exception if its negative). The Switch() method should simply print out to
System.out a message indicating the state of the bulb after it has changed.
public class ThreeWayLamp {
public String[] States = {"Off","LowLifght", "MediumLifght", "HighLight"}; // an array of the 4 states
public void Switch(int switchState){
//used an if condition to determine what to print based on the parameter switchState
if ((switchState <= States.length) && (switchState >= 0)){
System.out.println(States[switchState]);
}else if (switchState < 0 ){
System.out.println("Wrong input, try again with diffrent number");
}else if (switchState >= States.length){
} //This condition is the issue, how to form a condition that will solve this problem
}
If the parameter is larger than the array's length, an error will occur, so the issue is how to form a condition that will make the array loop again around itself when it reaches its last index.
For example, if the input was 5, then the method should print LowLight.
Is there a possible condition or function that could solve this issue, or should I change the entire structure of the code?
You can solve this problem by using a modulo operator:
System.out.println(States[switchState % States.length]);
Instead of using the less than condition, you can try using mod to repeat the indexes of your String array.
Try below code:
public class ThreeWayLamp {
public String[] States = {"Off","LowLifght", "MediumLifght", "HighLight"}; // an array of the 4 states
public void Switch(int switchState){
if ((switchState > 0){
System.out.println(States[switchState % States.length]); // states.length = 4 in your case
} else {
System.out.println("Wrong input, try again with diffrent number");
}
}
Using modulo you can ensure the index will always be within the size of the array
4 % 4 = 0
5 % 4 = 1
6 % 4 = 2
7 % 4 = 3
8 % 4 = 0
9 % 4 = 1
...
public void Switch(int switchState){
if ((switchState < States.length) && (switchState >= 0)){
System.out.println(States[switchState]);
} else if (switchState < 0 ){
System.out.println("Wrong input, try again with diffrent number");
} else {
Switch(switchState % 4);
// or
// System.out.println(States[switchState % 4]);
}
}
Also, variable and method names should start with a lower case

The code showing Time Limit Exceed erroe, could some one explain, where is problem in this code [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 last year.
Improve this question
LeetCode 485
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
---------Solution:-------
public int findMaxConsecutiveOnes(int[] nums) {
int maxConsSize = Integer.MIN_VALUE;
int i = -1, j=-1, k=0;
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
return maxConsSize;
}
Warning: This is not direct answer (for this "do my homework" question)
You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).
The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" + k) into your program (in a while loop).
You might want to watch this youtube video.
You have an infinity loop. Try run this:
public class Test {
public static void main(String[] args) {
int maxConsSize = Integer.MIN_VALUE;
int[] nums = {1,1,0,1,1,1};
int i = -1, j=-1, k=0;
System.out.println(nums.length);
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
System.out.println("k = " + k);
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
System.out.println(maxConsSize);
}
}
Output:
6
k = 1
k = 2
After reading the first 0 you are in infinite loop. You have made this task very complicated :)
It's probably not the best solution, but it should be faster
public int findMaxConsecutiveOnes(int[] nums) {
int maxCons = 0;
int currentCons = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (currentCons > maxCons) {
maxCons = currentCons;
}
currentCons = 0;
} else {
currentCons++;
}
}
if (currentCons > maxCons) {
maxCons = currentCons;
}
return maxCons;
}
}
There are two basic forms of loops:
for-each, for-i or sometimes called ranged for
Use that for a countable number of iterations.
For example having an array or collection to loop through.
while and do-while (like until-loops in other programming languages)
Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!
Your issue: infinite loop
You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.
The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.
Recommendation to solve
Would recommend to start with a for-i here:
// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i++) {
// do something with num[i]
System.out.println(num[i]):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no counting, etc. inside the loop-body
Even simpler and idiomatic pattern is actually to use a for each:
for(int n : nums) {
// do something with n
System.out.println(n):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no index required, suitable for arrays or lists
no counting at all
See also:
Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks

Printing "*" with recursion [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
I would need some help to solve one exercise. In this method I have to print the number of asterisks ("*") that are equal of 2 of power of x.
For example, if I have 2 of power of 2 it should print 4 asterisks ("****");
I have a method that returns me the right number, but I have problems using that number for printing those asterisks.
Here is my code:
public static int writeStars(int number) {
if (number == 0) {
return 1;
} else {
int number2 = 2 * writeStars(number - 1);
System.out.println(" number " + number2);
return number2;
}
}
Here's one idea for solving the problem, without giving away the solution in code.
Your thoughts are on the right track, realizing that 2x = 2 * 2x-1. To print 2x * characters, you can print 2x-1 twice. In your recursive method, have your base case print one * character, and have your recursive case make the recursive call twice, passing the appropriately adjusted value.
One way to do it is to create a string of 2^(i-1) stars at the i-th iteration. So, for 4 iterations (x=4), you will have 8,4,2,1 stars for each iteration. You can return the string of stars for each iteration and concatenate them to get the final string.
The terminating condition will be when the input size is 0. This code might help:
public static String writeStars(int y) {
//y is 2^x
if( y == 0)
return "";
int num_stars = y - y/2;
StringBuffer stars_Buffer = new StringBuffer(num_stars);
for (int i = 0; i < num_stars; i++){
stars_Buffer.append("");
}
return stars_Buffer.toString() + writeStars(y/2);
}
Call writeStars with input 2^x:
writeStars(Math.pow(2, x));
Because it is a return method in your client you should have
int num = writeStars(someNum);
Then to print, you just need a simple for loop
for(int i=0; i < num; i++)
System.out.print("*");

java.lang.stackoverflowerror recursion [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 7 years ago.
Improve this question
public static boolean sum_rec(int[] A, int n, int k) {
return addition(A, n, k, 0);
} // end sum_rec
private static boolean addition(int[] A, int n, int k, int i) {
if (k == A[i] + A[n - 1 - i]) {
return true;
}
else if (n == 1){
return false;
}
else
return addition(A, n, k, i++);
}
Hi, I am getting stackoverflow error whenever I try to run the following code. It returns true if there are any two numbers in array that sum up to a value k but I cant seem to find the error. Any help will be appreciated. Also what is the running time of this?
You need a base case that will end the recursion (return false) in the case that
k == A[i]+A[n-1-i]
is never true.
n == 1 is not that base case since n doesn't change during the recursion ... a base case that depends on the variable that changes during recursion
There are multiple problems with your code. One that hasn't been pointed out yet is that you think you're calling the method recursively by adding 1 to the last parameter, but you're not. This line:
return addition(A, n, k, i++);
has a post-increment operator. This means that it will add 1 to i but it will use the old value of i as the parameter. So it's the same as:
int oldValueOfI = i;
i = i + 1;
return addition(A, n, k, oldValueOfI);
You can see that you're calling the method recursively with the exact same values that it was called last time, so of course it will recurse infinitely. Although I wouldn't use recursion for this program, if you really want to, change the call to
return addition(A, n, k, i + 1);
You're not going to use i afterwards, so you don't need to change the value. (Note that each recursive call has its own i variable; the variable is not shared between the calls. So incrementing i will not have any impact on the i used by the next recursive call, the previous recursive call, or any other recursive call.)
Also note that this will not solve your problem, but making this change might help you figure out what to do next when your program starts blowing up on a different exception.

Does my program have a runtime error or does my computer not have the power to run my program? [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 9 years ago.
Improve this question
So I started the Euler Project and the first problem was very easy, however I cannot get the answer because the program I created is not running. It compiles fine but when I run it, it never runs. Project Euler says that the problems " with efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute." Which leads to my question. Am i stuck in an infinite loop or does my computer not have the power to run my program?
The problem is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class Euler1
{
public static void main(String[] args)
{
double x = 1;
int count = 0;
int total = 0;
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
System.out.println(total);
}
}
Your program is wrong.
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
Notice that x is only incremented if the condition is true. x starts at 1, so the condition is not true, so x never gets incremented and stays at 1.
Also, x/3 == (int)x and x/5 == (int)x are not correct tests for divisibility. Neither of them are ever true unless x is 0.
The problem is that if your if condition is false in the while loop, x never gets incremented...
(and it will always be false unless x is 0)
You are getting stuck in an infinite loop. Your if-statement is never being called because it will never return true unless x is 0, and thus your x variable is never being incremented. I would suggest looking into the % (modulus) operator for this problem.

Categories