I'm trying to recursively compute the fibonacci sequence to 100, store those returned values into an array using a the buildArray method, then print values stored in the array. I am getting a "cannot be resolved to a variable" compilation error when I try to print A[N] in the main method. I'm using longs because I'm computing the series up to 100, although I don't know if it's necessary to use longs.
If I substitute F(N) for A[N] the code works, but I need to put the values into an array and print that array. Does this code even store the values in an array? I'm just starting java, thanks.
public class MyFibonacci {
public static final int MAX = 100;
public static long[] buildArray(int MAX, int N) {
long[] A = new long[MAX];
A[0] = 0;
A[1] = 1;
for(N = 2; N < MAX; N++)
A[N] = F(N);
return A;
}
public static long F(int N) {
if(N == 0)
return 0;
if(N == 1)
return 1;
return F(N - 1) + F(N - 2);
}
public static void main(String[] args) {
for(int N = 0; N < MAX; N++)
System.out.println(N + " " + A[N]);
}
}
You have declared A[] within the scope of buildArray(int MAX, int N). As a result, A[] is not accessible outside of buildArray. You need to move your declaraction of long A[] to a class variable.
Additionally, you actually need to run buildArray for the array to be constructed.
For future reference, I highly recommend using proper tabbing structures. It makes it much easier to see what's happening. I've edited your code (though it will have to be approved) to include this.
Here's the code for what you need, I think:
public class MyFibonacci{
public static final int MAX = 100;
long[] A = new long[MAX];
public static long[] buildArray(int N){
A[0] = 0;
A[1] = 1;
for (N = 2; N < MAX; N++){
A[N] = F(N);
}
return A;
}
public static long F(int N)
{
if (N == 0) return 0;
if (N == 1) return 1;
return F(N-1) + F(N-2);
}
public static void main(String[] args)
{
buildArray(<some number - not sure where you get it from? N by the way in buildArray()>);
for (int N = 0; N < MAX; N++)
StdOut.println(N + " " + A[N]);
}
}
The main problem is that you're never calling the buildArray function.
To get your code to work, you only need to add this to main:
long[] A = buildArray(MAX, 0);
Some other things:
You can remove the parameter N and just declare it in the function (or remove it all-together, see below).
You already have access to MAX, no need to pass it to the function.
The for-loop in buildArray is rather inefficient, you can set up the array inside F.
Given the below, A as a class variable is cleaner than passing it around.
Finally, the code:
static int MAX = 100;
static long[] A;
public static void buildArray()
{
A = new long[MAX+1];
F(MAX);
}
public static long F(int N)
{
long val;
if (N < 2)
val = N;
else if (A[N] != 0) // HEY! It's already calculated! Awesome! Just return it.
return A[N];
else
val = F(N-1) + F(N-2);
A[N] = val;
return val;
}
public static void main(String[] args)
{
buildArray();
for (int N = 0; N <= MAX; N++)
System.out.println(N + " " + A[N]);
}
Since you can allocate array memory, it makes good sense to utilize it during calculation. Consider this method:
public static long[] f_a(int n) {
long[] a = new long[n];
a[1] = 1;
for (int i = 2; i < n; i++)
a[i] = a[i-1] + a[i-2];
return a;
}
Related
How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad
I am having problems understanding a program I need to write for class. My program works as it should, but the problem states that it wants me to not print within my methods. I am confused on how I should output my values because my methods must be void according to the problem (which doesn't return anything) and I can't print inside of them.
Here is the question:
Design and implement a java program (name it ArrayMethods), that defines 4 methods as follows:
int arrayMax (int[] array)
int arrayMin (int[] array)
void arraySquared (int[] array)
void arrayReverse (int[] array)
Test your methods by creating an array of length 5 within your main method and filling it with random numbers between 1 and 1000. Your program should then display the original array, display the smallest number in the array, display the greatest number in the array, display the revered array, and display the square of each value in the array. You main method shoudl invoke each method exactly once, with each invocation use the original array as the actual parameter. No printing within the methods. Document your code, and organize/space your outputs properly. Use escape characters and formatting objects when applicable.
So again my question is: How do I use those methods without printing anything if I can't return a value? If anyone could give me a clue on how to solve this, it would be greatly appreciated.
import java.util.Random;
import java.util.Arrays;
public class ArrayMethods
{
public static void main (String[] args)
{
int[] array = new int[5];
array[0] = (int)(Math.random() * (1000 - 1)) + 1;
array[1] = (int)(Math.random() * (1000 - 1)) + 1;
array[2] = (int)(Math.random() * (1000 - 1)) + 1;
array[3] = (int)(Math.random() * (1000 - 1)) + 1;
array[4] = (int)(Math.random() * (1000 - 1)) + 1;
System.out.println("The values within the array are: " + Arrays.toString(array));
System.out.println("The maximum value within the array is: " + arrayMax(array));
System.out.println("The minimum value of the array is: " + arrayMin(array));
System.out.print("The values within the array (squared) are: ");
arraySquared(array);
System.out.print("\n");
System.out.print("The array reversed is: ");
arrayReverse(array);
}
public static int arrayMax (int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static int arrayMin (int[] array)
{
int min = 1000;
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public static void arraySquared (int[] array)
{
int[] array2 = new int[5];
for (int i = 0; i < array.length; i++)
{
array2[i] = array[i] * array[i];
System.out.print(array2[i]);
while ( i < array.length - 1)
{
System.out.print(", ");
break;
}
}
}
public static void arrayReverse (int[] array)
{
for(int i = array.length - 1; i >= 0; i--)
{
System.out.print(array[i] + " ");
}
}
}
For the void functions, in C# you'd simply use an "out" or "ref" keyword. If they insist on Java, Java doesn't have an equivalent, but you can do something like that with an object.
public class PassArray
{
public int[] array;
public PassArray(int[] array)
{
this.array = array;
}
}
public static void Reverse(PassArray arrayHolder)
{
int[] reversed = new int[arrayHolder.array.Length];
int j = 0;
for (int i = arrayHolder.array.Length - 1; i >= 0; i--)
{
reversed[j] = arrayHolder.array[i];
j++;
}
arrayHolder.array = reversed;
}
static void Main(string[] args)
{
int[] toReverse = new[] { 10, 30, 2, 1, 3, 100, 340 };
PassArray passedObject = new PassArray(toReverse);
Reverse(passedObject);
// passedObject.array will now have the reversed array
}
Obviously this could can be improved but it should at least give the right idea.
I've implemented the Heap's algorithm for finding all permutations of the elements of array A:
//A = {1, 2, 3, 4}; B = perms(A) ; num_row(B) = (4!+1) and B[0][0] = 4!;
//This is B.R. Heap's algorithm
public static void perms(int [] A, int [][]B, int n)
{
if (n == 1)
{
int k = B[0][0];
for (int i = 0; i < A.length; i++)
{
B[k + 1][i] = A[i];
}
B[0][0]++;
}
else
{
for (int i = 0; i < n - 1 ;i++)
{
perms(A, B, n-1);
if (n % 2 == 0)
{
swap(A, i, n - 1);
}
else
{
swap(A, 0, n - 1);
}
}
perms(A, B, n - 1);
}
}
public static void swap(int[] A, int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
I'm new to Java. The problem is I want to have B as the output (return) of the function perms(A) , but in this implementation, I have to initialize a int[n! + 1][A.length] B array before calling the function. How can I do it?
Is there anything like private variable or anything in java to help a recursive function to remember a variable from a former call?
Thanks
You can create an "entering" method to recursion like this:
public static int[][] perms(int[] a){
int[][] perms = new int[factorial(a.length)+1][a.length];
perms(a,perms,a.length);
return perms;
}
Method factorial is well know method and can be found on Google for example
Wondering if n parameter is neccessary
EDIT
it is not neccessary (above corrected)
EDIT
By my test the k variable is just incrementing, so I would use static variable like this:
private static int counter = 0;
// your code here, following is a part of your perms method
if (n == 1)
{
for (int i = 0; i < A.length; i++)
{
B[counter][i] = A[i];
}
counter++;
}
//and my code corrected too:
public static int[][] perms(int[] a){
int[][] perms = new int[factorial(a.length)][a.length]; //+1 is not necessary
counter=0; //necessary to call it again
perms(a,perms,a.length);
return perms;
}
I have been staring at this for almost a week and do not know how to implement the java code.
First, I wrote a recursive Hofstadters Q Sequence that computes the n(th) number in Hofstadter’s Q-sequence, for n ≥ 1 which is as follows
Ps. the Hofstadters Q Sequence is sort of like the Fibonacci sequence, only that it is defined as follows:
Q(1) = 1, Q(2) = 1, and
Q(n) = Q(n − Q(n − 1)) + Q(n − Q(n − 2)), for n > 2
public static int Hofstadters(int n)
{
int result;
if (n < 3)
result = 1;
else
result = Hofstadters(n - (Hofstadters(n-1))) + Hofstadters(n - (Hofstadters(n-2)));
return result;
}
this works perfectly fine. Now I was challenged to write this code using a loop instead of recursion, and an array (to store numbers in the sequence as I compute them from Q(1) to Q(n)).
The idea is that I will put the Q(i) element into position i of the array, from 1 to n.
I do not even know how to start it. So far I have written just the code below and have been practically staring at my screen ever since:
public static void QSequence(int n)
{
int result;
int [] arr;
int value;
arr = new int [n-1];
arr[0] = 1;
arr[1] = 1;
for(int count = 2; count< arr.length; count++)
{
//code
}
}
Please any help and hints will be much appreciated, thanks
It should work:
package snippet;
public class Snippet {
public static void main(String[] args) {
System.out.println(QSequence(10));
}
public static int QSequence(int n) {
int result;
int[] arr;
int value;
arr = new int[n];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - arr[i - 1]] + arr[i - arr[i - 2]];
}
return arr[n - 1];
}
}
When I run Countdown.class I get the following output:
263845041
-1236909152
-973064111
2084994033
1111929922
-1098043341
13886581
-1084156760
-1070270179
2140540357
Blast Off!
The numbers before "Blast Off!" ought to be the first 10 Fibonacci numbers. My source code is as follows.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return 1;
return fib(n-1) + fib(n-2);
}
public static long fastfib(int n) {
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i <= n; n++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
and the class that implements the fastfib method is:
public class Countdown {
public static void countdown(int n) {
if (n == 0) System.out.println("Blast Off!");
else {
System.out.println(Fibonacci.fastfib(n));
countdown(n - 1);
}
}
public static void main(String[] args) {
countdown(10);
}
}
Though your fastfib() method returns long, the calculations are done on ints.
You are encountering integer overflow.
Make sure to declare a,b,c as longs and NOT as ints. If you want even larger numbers (that are out of range for longs as well) - you might want to have a look on BigInteger (and use it).
EDIT: As mentioned by #ExtremeCoders in comment, there is another issue in the code in your for loop:
for (int i = 0; i <= n; n++) should be for (int i = 0; i <= n; i++), you want to increase i - not n.
In addition to the other answers,
for (int i = 0; i <= n; n++) {
should be
for (int i = 0; i <= n; i++) {
// ^ that's an i
Change the datatypes of a,b and c to long, and it will start working fine. Your numbers are crossing the limits for int.
You should user BigInteger insted of long
import java.math.BigInteger;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
int result = n.compareTo(BigInteger.valueOf(1)); // returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
if (result != 1) return BigInteger.valueOf(1);
return fib(
n.subtract(
BigInteger.valueOf(1).add
(n.subtract
(
BigInteger.valueOf(-2)
)
)
)
);
}
public static BigInteger fastfib(int n) {
BigInteger a = BigInteger.valueOf(0);
BigInteger b = BigInteger.valueOf(1);
BigInteger c = BigInteger.valueOf(0);
for (int i = 1; i < n; i++) {
c = a.add(b);
a = b;
b = c;
}
return c;
}
}