Runtime error - Java [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 8 years ago.
Improve this question
I was trying to find sum of even fibonacci number for a given set of N inputs(obtained from stdin)
This code is working well for some test cases but printing runtime error(No details given) for a test case.
Link for question: https://www.hackerrank.com/contests/projecteuler/challenges/euler002
code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;
public class Solution {
public static Integer[] convert(int[] chars) {
Integer[] copy = new Integer[chars.length];
Arrays.fill(copy, 0);
for(int i = 0; i < copy.length; i++) {
copy[i] = Integer.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int x, max;
int a[], sum[], fib[];
Scanner in = new Scanner(System.in);
x = in.nextInt();
a = new int[x];
sum = new int[x];
for(int i=0;i<x;i++)
{
a[i] = in.nextInt();
}
Integer[] b = convert(a);
max = Collections.max(Arrays.asList(b));
fib = new int[max];
if (max >1)
{
fib[0]=1;
fib[1]=1;
}
for(int i=2;i<max;i++)
{
fib[i] = fib[i-1]+fib[i-2];
}
for(int i =0;i<x;i++)
{
for(int j = 0;fib[j]<a[i];j++)
{
if(fib[j]%2 ==0)
sum[i] = sum[i] + fib[j];
}
}
for(int i=0;i<x;i++)
{
System.out.println(sum[i]);
}
}
}
Any help is appreciated.
I'll be more thankful if you can help me with an optimized version of the same.

Your code would throw ArrayIndexOutOfBoundsEception in some cases.
Let's consider what you are doing :
You are getting an input x from user
Then you create array a with x elements, input by user
Then you find the max element of a
You create an array fib of max elements, and calculate fib[i] for each i from 0 to max-1
Suppose the user inputs : 2 2 2
max would be 2, so fib would contain two elements : {1,1}
Now, the following loop will cause the exception :
for(int i =0;i<x;i++) // x is 3
{
for(int j = 0;fib[j]<a[i];j++) // both fib[0] and fib[1] < a[0]
// fib[2] would throw the exception
It is not clear what you are trying to do with this nested loop, but clearly it doesn't work.

i think the problem is that the Recursive call stack in java is so deep,so the java compiler will print RE. and to optimize this problem, frist,you can use the dp method to solve this problem。the dp method is to decrease the repeat count to the problem.
the link is http://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92
hope to help you.

Related

Play with numbers problem from hackerearth ....i'm getting time limit exceed problem [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 2 years ago.
Improve this question
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
Input:
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Output:
print a single integer denoting the answer.
Constraints:
1<= N ,Q,L,R <= 10^6
1<= Array elements <= 10^9
import java.util.Scanner;
public class PlayWithNumbers {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
long n=obj.nextLong();
long qry=obj.nextLong();
long arr[]=new long[(int) n];
for (int i = 0; i <n ; i++) {
arr[i]=obj.nextInt();
}
for (int j = 0; j <qry ; j++) {
long sum=0;
double ans=0;
int L=obj.nextInt();
int R=obj.nextInt();
sum=(L+R)/2;
ans=Math.floor(sum);
System.out.println((int) ans);
}
}
}
First: your solution is wrong. The question clearly is stating that L and R are the indexes of the subarray (not the value), and you are using as value to find the mean value.
Second: Scanner class is very easy, need less typing but not recommended as it is very slow. Instead, use BufferReader.
Here is my solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PlayWithNumbers {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n=Integer.parseInt(st.nextToken());
long qry=Integer.parseInt(st.nextToken());
long arr[]=new long[(int) n];
st = new StringTokenizer(br.readLine());
// read every number, adding with previous all numbers and store in the array index
arr[0] = Integer.parseInt(st.nextToken());
for (int i = 1; i <n ; i++) {
arr[i]=arr[i-1]+Integer.parseInt(st.nextToken());
}
for (int j = 0; j <qry ; j++) {
long sum=0;
double ans=0;
st = new StringTokenizer(br.readLine());
int L=Integer.parseInt(st.nextToken());
int R=Integer.parseInt(st.nextToken());
// check if the value 1 then don't subtract left value (as in that case there won't be any left value
// otherwise subtract just left most value from the array
if (L == 1) {
sum=arr[R-1]/(R-L+1);
} else {
sum=(arr[R-1] - arr[L-2])/(R-L+1);
}
ans=Math.floor(sum);
System.out.println((int) ans);
}
}
}
Let me know if you need any clarification.

Please help I can not see the error [duplicate]

This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 4 years ago.
I am using Intellj Idea and I am playing with ArrayLists, Arrays and a sorting algorithm I want to generate 5 random grades put them into an ArrayList convert the values of the ArrayList into an Array. Sort the Array values from least to greatest and print to screen the grades before and after sort here is what I have:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
public class Grades {
public static void main(String args[])
{
ArrayList <Integer> scores = new ArrayList<Integer>();
for(int i = 0; i < 5; i++)
{
scores.add((int) (Math.random() * 30 + 1));
}
for (int i =0; i < scores.size();i++)
{
System.out.println(scores.get(i));
}
int arrayOne[] = new int[scores.size()];
arrayOne = scores.toArray(new int[scores.size()]);
The last line is where I have the problem. Intellij says: no suitable method found for toArray(int[]).
Is my syntax wrong?
Did I forget to import a library?
Is it possible for ArrayLists and Arrays to interact in this way?
Please help.
int first,second, temp=0;
for(first=0; first < arrayOne.length -1; first++)
{
for (second = 0; second < arrayOne.length - 1 - first; second++)
{
if(arrayOne[second] < arrayOne[second +1])
{
temp = arrayOne[second];
arrayOne[second] = arrayOne[second + 1];
arrayOne[second+1] = temp;
}
}
}
I haven't been able to run this bit to see if it sorts the way I want it too yet.
for(int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
}
}
As you can see from toArray(T[]) contract it takes an array containing a reference type and int is not a reference type.
Change your code as to arrayOne is of type Integer[]
Integer[] arrayOne = scores.toArray(new Integer[scores.size()]);

How to add and print prime numbers [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
The idea is to type two numbers in the command line. The first being the start and the second being the number of prime numbers after the first number are displayed. For instance if the input was 16 3 the output would be 17 19 23
These numbers would be stored into an array. I've been trying many different things but they haven't worked so far.
I only have this right now
{
public static void main (String[] args)
{
int start =Integer.parseInt(args[0]);
int count =Integer.parseInt(args[1]);
int[] prime = new int[count];
public static boolean check(int a)
{
if (a%2==0)
return false;
for(int i=3;i*i<=a;i+=2)
{
if(a%i==0)
return false;
}
return true;
}
}
Your check function is great. What you need is just a while loop to add prime number to prime[]
public static void main (String[] args)
{
int start =Integer.parseInt(args[0]);
int count =Integer.parseInt(args[1]);
int[] prime = new int[count];
int i = 0;
while (i < count){
if(check(start)){
prime[i] = start;
i++;
}
start++;
}
for (int p : prime){
System.out.println( p);
}
}
If you want a program to do something N times, you can use a loop.
Since this feels like HW I will provide an analogous problem. Count N odd numbers:
int numbersToCount = 5;
int count = 0;
int start = 1;
while (count < numbersToCount) {
if (start % 2 == 1) {
count = count + 1;
// opportunity to print number you are interested in
}
start = start + 1;
}

This program in java doesn't stop executing [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 8 years ago.
Improve this question
I have written this java program for sorting some numbers. But it doesn't stop executing. Can you help me with it?
package inplacesort;
import java.util.*;
public class InplaceSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Vector <Integer> intList = new Vector <Integer> ();
//getting the numbers from the user
char ans = 'y';
while (ans == 'Y' || ans == 'y')
{
System.out.print("Enter a Number: ");
intList.addElement(console.nextInt());
System.out.print("Do You Want to Continue?(Y/N)");
ans = console.next().charAt(0);
}
System.out.println("Before Sorting the Numbers: " + intList);
for (int i = 1; i < intList.size(); i++)
{
int j = i - 1;
while (j > 0 && intList.elementAt(i) < intList.elementAt(j))
{
j--;
}
for (int k = intList.size() - 1; k >= j; k--)
{
intList.insertElementAt(intList.elementAt(k),k + 1);
}
intList.insertElementAt(intList.elementAt(i+1),j);
intList.removeElementAt(i+1);
}
System.out.print(intList);
}
}
Your problem is with intList.size() in the k & i loops. This is not be as what you would expect it. When I debugged your code the value of k was 425996.
Edit :
When i debugged it more I saw that because of you mutating the vector within it self it keeps increasing in size. If you let your program run for a few minutes you will get out of memory error.
Please don't mutate the object you are looping though it. Either make a copy of it and the loop though one of them and mutate another or start with a fresh one & keep adding the values to it while looping over the older one.
System.out.println("Before Sorting the Numbers: " + intList);
List<Integer> sortList = new ArrayList<Integer>();
int minVal;
int index=0;
int size = intList.size();
for (int i = 0; i < size; i++)
{ minVal=Integer.MAX_VALUE;
for (int j = 0; j < intList.size(); j++)
{
if(intList.get(j) < minVal){
index=j;
minVal=intList.get(j);
}
}
intList.remove(index);
sortList.add(minVal);
}
System.out.print("After Sorting the Numbers: "+ sortList);
The reason is because your value for j is ALWAYS 1 less than the value for i. Therefore, infinite while loop.

rolling dice using arrays [closed]

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 9 years ago.
Improve this question
simple beginner Java question. I just learned how to use arrays and it's still a little confusing to me. My goal is to simply roll a number of dice a number of times and then project it as a sum, frequency, and percentage. I'm sure I'm doing something dumb, but I'm overlooking it!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}
From what I can see the question is how can you store the previous roles of the dice. And I believe your problem is with this method:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
I would change this to
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
This will build up an array storing each dice roll - if that is of course what you are looking for...
Two things.
First, this loop will inevitably throw ArrayIndexOutOfBoundsException ("element" total[total.length] is out of bounds)
for (int i=0; i<=total.length; i++)
total[i] = 0;
You should use < instead of <=.
for (int i=0; i<total.length; i++)
total[i] = 0;
Second, this line here:
for(int k=2; k<total.length; k++);{
You have an empty loop here. You should remove the semicolon before the {:
for(int k=2; k<total.length; k++){
Now your code compiles, doesn't throw exceptions on the start, and prints a pretty table.
That's a start.
for(int k=2; k<total.length; k++);{
You need to remove the ; symbol from your loop as 'k' will not be resolved in the loop as you have terminated it. The format is for(x, x, x) {
The next thing to look at now is:
Dice: 1
Rolls: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Lab1.main(Lab1.java:26)
Hint:
total[i] = 0; // this line is the problem.
Look at your <= in the loop.
for (int i=0; i<total.length; i++)
Simply chaging it to < results in this:
Dice: 1
Rolls: 1
Sum Frequency Percentage
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0

Categories