Writing Fibonacci sequence in Java starting from certain term - java

I am trying to write a Fibonacci sequence generator based on Java. I saw many examples on the Internet for instance:
public class Fibonacci {
public static void main(String[] args) {
generateFibonacci(20); // generate the first 20 fibonacci numbers
}
public static void generateFibonacci(long limit) {
long first = 0;
long second = 1;
System.out.print(first+", "+second);
for(long i=1;i<limit;i++) {
long next = first + second;
System.out.print(", "+next);
first = second;
second = next;
}
System.out.println();
}
}
And it works fine. The problem is that not only I want to generate the first 20 numbers, but I also need to specify a starting point. For example:
public List<Long> generateFibonacci(long startFrom, long numberTerms) {
}
Doing:
generateFibonacci(5, 10);
Should output:
8l
13l
21l
34l
55l
89l
144l
233l
377l
I have tried the following code but it doesnt seem to be performing the desired action:
public class example {
public static void main(String[] args) {
generateFibonacci(10, 5);
}
public static void generateFibonacci(long limit, long startPoint) {
long first = 0;
long second = 1;
long endPoint = startPoint + limit;
System.out.print(first + ", " + second);
for (long i = 1; i < endPoint; i++) {
long next = first + second;
if (i > startPoint) {
System.out.print(", " + next);
}
;
System.out.print(", " + next);
first = second;
second = next;
}
}
}
Any ideas on how to achieve this in an efficient way?

as you said output must be like this
8
[13, 21, 34, 55, 89, 144, 233, 377]
and you want to return a list of fibonacci numbers
you can return a list as you want in this way !
public static void main(String[] args) {
List<Long> list = generateFibonacci(10, 5);
System.out.println(list.size());
System.out.println(Arrays.toString(list.toArray()));
}
public static List<Long> generateFibonacci(long limit, long startPoint) {
List<Long> list = new ArrayList<>();
long first = 0;
long second = 1;
long endPoint = startPoint + limit - 1;
//System.out.print(first + ", " + second);
if (startPoint==0){
list.add(0);
list.add(1);
}else if (startPoint ==1){
list.add(1);
}
for (long i = 2; i < endPoint; i++) {
long next = first + second;
if (i > startPoint) {
// System.out.println(next);
list.add(next);
}
first = second;
second = next;
}
return list;
}

Line 10 is always going to print 0 and 1, so remove that.
You have a semi-colon on line 16, and line 17 prints all Fibonacci numbers which is why you get two of the ones you want
Try:
public class example {
public static void main(String[] args) {
generateFibonacci(10, 5);
}
public static void generateFibonacci(long limit, long startPoint) {
long first = 0;
long second = 1;
long endPoint = startPoint + limit;
for (long i = 1; i < endPoint; i++) {
long next = first + second;
if (i == startPoint) {
System.out.print(next);
}
else if ( i > startPoint){
System.out.print(", " + next);
}
first = second;
second = next;
}
}

if (i > startPoint) Here you do not have to put conditions on i but on next.
The problem is that not only I want to generate the first 20 numbers,
but I also need to specify a starting point.
Also, I'm not sure why you are printing the first two elements i.e. 0 and 1. I have removed the sysout() to meet the startPoint condition as you specified.
Here is the corrected code snippet:
public static void generateFibonacci(long limit, long startPoint) {
long first = 0;
long second = 1;
long endPoint = startPoint + limit;
long next = first + second;
for (long i = 1; i < endPoint; i++) {
if (next > startPoint) {
System.out.print(next + ", ");
}
first = second;
second = next;
next = first + second;
}
}
Output:
8, 13, 21, 34, 55, 89, 144, 233, 377, 610

Since you have to calculate the initial Fibonacci numbers anyway, just use the standard method and do this:
public static void generateFibonacci(long limit, long startPoint) {
return generateFibonacci(limit).subList(startPoint - 1, limit);
}

Related

How do I fix this Java BubbleSort algorithm?

I'm doing a Java programming assignment which involves bubble sorting a .dat file BetelgeuseNames.dat with strings in it alphabetically. My AP Computer Science A teacher told me my code is correct, but it still gives the wrong output.
There are three classes called BubbleSort, BubbleSortTimer, and StopWatch. The program runs from BubbleSortTimer.
BubbleSort:
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.io.FileWriter;
import java.io.IOException;
public class BubbleSort {
// Private instance variables:
private ArrayList<String> list;
private int number;
public BubbleSort(ArrayList<String> a_list) {
list = a_list;
}
public void swap(int first, int second) {
String temp1 = list.get(first);
String temp2 = list.get(second);
list.set(first, temp2);
list.set(second, temp1);
}
public int getNumber() {
String numStr;
numStr = JOptionPane.showInputDialog("How many names do you want to sort?");
number = Integer.parseInt(numStr);
return number;
}
public void printSorted() {
try {
FileWriter writer = new FileWriter("sorted.dat");
for (int i = 0; i < number; i++) {
writer.write(list.get(i) + "\n");
}
writer.close();
} catch (IOException exception) {
System.out.println("Error processing file: " + exception);
}
}
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = 0; j < number - i - 1; j++) {
if (list.get(i).compareTo(list.get(i+1)) > 0) {
swap(i, i + 1);
}
}
}
} // End method
}
BubbleSortTimer:
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JOptionPane;
import java.io.IOException;
public class BubbleSortTimer {
private ArrayList<String> list = new ArrayList<String>();
public void readNames() {
try {
FileReader reader = new FileReader("BetelgeuseNames.dat");
BufferedReader in = new BufferedReader(reader);
boolean done = false;
String name;
while (done == false) {
name = in.readLine();
if (name == null) {
done = true;
} else {
list.add(name);
}
}
reader.close();
} catch (IOException exception) {
System.out.println("Error processing file: " + exception);
}
} // End method
public void runSort() {
readNames();
StopWatch timer = new StopWatch();
BubbleSort sorter = new BubbleSort(list);
int number = sorter.getNumber();
timer.start();
sorter.bubbleSort();
timer.stop();
sorter.printSorted();
String msg = "Number of names sorted: " + number + "\nMilliseconds required to sort: " + timer.getElapsedTime() + "\nOutput file is \"sorted.dat\"";
JOptionPane.showMessageDialog(null, msg);
}
public static void main(String[] args) {
BubbleSortTimer bubble = new BubbleSortTimer();
bubble.runSort();
}
}
StopWatch:
/**
* A stopwatch accumulates time when it is running. You can
* repeatedly start and stop the stopwatch. You can use a
* stopwatch to measure the running time of a program.
* from section 18.2 of Horstmann's CCJ
*/
public class StopWatch {
/**
* Constructs a stopwatch that is in the stopped state
* and has no time accumulated.
*/
public StopWatch() {
reset();
}
/**
* Starts the stopwatch. Times starts accumulating now.
*/
public void start() {
if (isRunning) return;
isRunning = true;
startTime = System.currentTimeMillis();
}
/**
* Stops the stopwatch. Time stops accumulating and is
* added to the elapsed time.
*/
public void stop() {
if (!isRunning) return;
isRunning = false;
long endTime = System.currentTimeMillis();
elapsedTime = elapsedTime + endTime - startTime;
}
/**
* Returns the total elapsed time.
#return the total elapsed time
*/
public long getElapsedTime() {
if (isRunning) {
long endTime = System.currentTimeMillis();
elapsedTime = elapsedTime + endTime - startTime;
startTime = endTime;
}
return elapsedTime;
}
/**
* Stops the watch and resets the elapsed time to 0.
*/
public void reset() {
elapsedTime = 0;
isRunning = false;
}
private long elapsedTime;
private long startTime;
private boolean isRunning;
}
Input:
Moewm
Bmlzvltcso
Aqxjor
Wwgjie
Qqqtpivd
Xgyhaerv
Wqpjwdvxjq
Ecsfnow
Zlptuqxctt
Jhtprwvopk
Expected Output:
Aqxjor
Bmlzvltcso
Ecsfnow
Jhtprwvopk
Moewm
Qqqtpivd
Wqpjwdvxjq
Wwgjie
Xgyhaerv
Zlptuqxctt
Actual Output:
Bmlzvltcso
Aqxjor
Moewm
Qqqtpivd
Wwgjie
Wqpjwdvxjq
Ecsfnow
Xgyhaerv
Jhtprwvopk
Zlptuqxctt
This is how Android did (binary) sorting (edited to fix this situation):
public void binarySort() {
int lo = 0; // sort start
for (int start=lo ; start < number; start++) {
String pivot = list.get(start);
// Set left (and right) to the index where list.get(start) (pivot) belongs
int left = 0;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left].
* pivot < all in [right, start].
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(list.get(mid)) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left] and
* pivot < all in [left, start], so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just reshifter in default case
switch (n) {
case 2: list.set(left + 2,list.get(left + 1));
case 1: list.set(left + 1,list.get(left));
break;
default:
if(n>0){
list.add(left,list.remove(left+n));
}
}
list.set(left,pivot);
}
}
This is how you can do (bubble) sorting:
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = i + 1; j < number; j++) {
if (list.get(i).compareTo(list.get(j)) > 0) {
swap(i, j);
}
}
}
}
BUBBLE SORTING V/S BINARY SORTING:
OFF TOPIC: As you can compare above, bubble sorting is easier to code/read/understand and is also faster as compared to binary sorting, because binary sorting (actually) uses array recreation many times which ofcourse takes more time compared to swap.
Because there is a problem with your bubbleSort() method. Please try this way.
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = 1; j < number - i; j++) {
if (list.get(j - 1).compareTo(list.get(j)) > 0) {
swap(j - 1, j);
}
}
}
}

Fastest way to search in milliseconds

I have to find what is the fastest way to search the max random number from my array within a range
So I create one method that search normal "using one thread" and another one that use threads
I have Class:MaxThread
import java.util.stream.IntStream;
public class MaxThread extends Thread {
private final int from;
private final int to;
public MaxThread(int[] tab, int from, int to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
long start = System.currentTimeMillis();
int max = IntStream.of(from, to)
.max()
.getAsInt();
long end = System.currentTimeMillis() - start;
System.out.println("Max number from threads is : " + max);
System.out.println("Founded in: " + end + " [ms] ");
}
}
Class: Main2
public class Main2{
public static void main(String[] args) {
int[] tab = new int[200000000];
for (int i = 0; i < tab.length; i++) {
tab[i] = random(0, 200000000);
}
int max = searchMax(0, 50000000);
System.out.println("Max number without using threads " + max);
MaxThread maxThread = new MaxThread(tab, 25000000, 150000000);
maxThread.start();
}
public static int random(int start, int end) {
Random rnd = new Random();
return rnd.nextInt(end - start + 1) + start;
}
public static int searchMax(int from, int to) {
long start = System.currentTimeMillis();
int max = IntStream.of(from, to)
.parallel()
.max()
.getAsInt();
long end = System.currentTimeMillis() - start;
System.out.println("Founded in: " + end + " [ms] ");
return max;
}
}
I count the time in ms inside the method but I want to see witch one was the fastest to find the number , but here is where I cannot find out the way to do it.
Can someone give me and hint please?

Fibonacci Recursive returns endless number

My code results with endless number "2", I don't understand why.
Also my tutor told me to add validation for negative values - I don't know how to do it.
public class FibonacciRecursive {
public static void main(String[] args) {
int fibonacciNumberOrder = 10;
do {
System.out.print(fibonacci(fibonacciNumberOrder) + " ");
} while (true);
}
public static long fibonacci(int fibonacciNumberInOrder) {
if (fibonacciNumberInOrder == 0) {
return 0;
}
if (fibonacciNumberInOrder <= 2) {
return 1;
}
long fibonacci = fibonacci(-1) + fibonacci(-2);
return fibonacci;
}
}
edit:
When I changed that line
long fibonacci = fibonacci(-1) + fibonacci(-2);
to:
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
It prints endless "55"
How should I change my code to make it work?
It happens because you calculate the Fibonacci number with constants instead of relative numbers to passed ones through, which is the point of recursion.
public static long fibonacci(int fibonacciNumberInOrder) {
if (fibonacciNumberInOrder == 0) {
return 0;
}
if (fibonacciNumberInOrder <= 2) {
return 1;
}
long fibonacci = fibonacci(fibonacciNumberInOrder - 1) + fibonacci(fibonacciNumberInOrder - 2);
return fibonacci;
}
The key changed line is:
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
You are recursing with constants! Change this
long fibonacci = fibonacci(-1) + fibonacci(-2);
to
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
And, in your while loop in main - you need to modify fibonacciNumberInOrder
int fibonacciNumberOrder = 1;
do {
System.out.print(fibonacci(fibonacciNumberOrder) + " ");
fibonacciNumberOrder++;
} while (true);

Loop will not execute properly

I am writing a program for class and the loop seems to not execute correctly. It always returns the value for i as 0. The rest of the code seems to work as advertised, i is just not increasing in index value.
public class Day {
String strDay;
private int d = 0;
private String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String day;
public Day() {
return;
}
public Day(String strDay) {// this is my issue. I think I am going about this constructor all wrong
for (int i = 0; i < Days.length; i++) {
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
public int getDay() {
return d;
}
public void nexDay() {
int next;
if (d < 6) {
next = (this.d) + 1;
System.out.println("Next Day is :" + Days[next]);
} else {
next = 0;
System.out.println("Next Day is :" + Days[next]);
}
}
public void prevDay() {
int prev = 0;
if ((d > 0) && (d < 6)) {
prev = (this.d) - 1;
System.out.println("previous day is " + Days[prev]);
} else
System.out.println("previous day id " + Days[6]);
}
public int calcDay(int num) {
int newDay;
this.d = d + num;
newDay = this.d % 7;
System.out.println("calc day is" + Days[d]);
return newDay;
}
public void print() {
System.out.println("day is " + Days[d]);
}
public static void main(String[] args) {
String day;
Day Callmethod = new Day();
Scanner console = new Scanner(System.in);
System.out.println("enter a day of the week");
day = console.nextLine();
Callmethod.print();
Callmethod.nexDay();
Callmethod.prevDay();
Callmethod.getDay();
}
}
Well, this
Day Callmethod = new Day();
is calling your empty constructor. Not your constructor with a loop (which takes a String). Also, Java variables start with a lower case letter (Callmethod looks like a class). I think you were looking for something like
Day day = new Day("SUNDAY");
Also, your if needs braces or the return will be invoked without doing anything (unless it matches on the first entry) like
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i])) {
d = i;
return;
}
}
try change this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
for this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
{
d = i;
return;
}
}
}
Without the curly braces your conditional block will be only the next line of code. So your loop was only running once
public Day(String strDay) {
for (int i = 0; i < Days.length; i++) {
if (strDay == Days[i])
d = i;
return;
}
}
If I understood it clearly this will work. If not, just explain me what the goal is on that for loop. And place the return statement outisde of the next bracket.

Fork and Join Java

Hey guys I need some help with my homework. I understand the way the Fork and Join Framework works, but my code does not join the results. Our exercise is to write a program, that counts the true values in an array. Sorry for any mistakes (bad grammar or something else) in this post, it is my first one.
Edit:
Thanks for all the requests here is my solution of this problem:
TrueFinder Class:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
class TrueFinder extends RecursiveTask<TrueResult>
{
private static final int SEQUENTIAL_THRESHOLD = 5;
private boolean[] trueData;
private final int start;
private final int end;
public TrueFinder(boolean[] data, int start, int end)
{
this.trueData = data;
this.start = start;
this.end = end;
}
public TrueFinder(boolean[] data)
{
this(data, 0, data.length);
}
protected TrueResult compute()
{
final int length = end - start;
int counter = 0;
if (length < SEQUENTIAL_THRESHOLD)
{
for (int i = start; i < end; i++)
{
if (trueData[i])
{
counter++;
}
}
return new TrueResult(counter);
}
else
{
final int split = length / 2;
TrueFinder left = new TrueFinder(trueData, start, start + split);
left.fork();
TrueFinder right = new TrueFinder(trueData, start + split, end);
TrueResult subResultRight = right.compute();
TrueResult subResultLeft = left.join();
return new TrueResult(subResultRight.getTrueCounter() +
subResultLeft.getTrueCounter());
}
}
public static void main(String[] args)
{
int trues = 0;
boolean[] trueArray = new boolean[500];
for (int i = 0; i < 500; i++)
{
if (Math.random() < 0.3)
{
trueArray[i] = true;
trues++;
}
else
{
trueArray[i] = false;
}
}
TrueFinder finder = new TrueFinder(trueArray);
ForkJoinPool pool = new ForkJoinPool(4);
long startTime = System.currentTimeMillis();
TrueResult result = pool.invoke(finder);
long endTime = System.currentTimeMillis();
long actualTime = endTime - startTime;
System.out.println("Array mit der Länge " + trueArray.length + " in"
actualTime + " msec dursucht und " + result.getTrueCounter() +
" von " + trues + " True Werten gefunden.");
}
}
And the result class:
public class TrueResult
{
private int trueCounter;
public TrueResult(int counter)
{
this.trueCounter = counter;
}
public int getTrueCounter()
{
return trueCounter;
}
}
The splitting task of your souce code is wrong as :
(1) your splitting isn't started from 0:
your start is 1
(2) fraction point is ignored for your splitting;
(granted that SEQUENTIAL_THRESHOLD=5 and trueArray.length = 13, your splitting is ignoring of the numbers from 11 to 12)
(3) if you modify for (1) and (2), the length of subtasks must be split not SQCUQNTIALTHRESHOLD.
So, the modifying source code is below:
else
{
int split = (length - 1 ) / SEQUENTIAL_THRESHOLD + 1;
TrueFinder[] subtasks = new TrueFinder[split];
int start = 0;
for(int i = 0; i < split - 1; i++)
{
subtasks[i] = new TrueFinder(trueData, start, start + SEQUENTIAL_THRESHOLD);
subtasks[i].fork();
start += SEQUENTIAL_THRESHOLD;
}
subtasks[split - 1] = new TrueFinder(trueData, start, length);
counter = subtasks[split - 1].compute();// better invoking compute than join
for (int i = 0; i < SEQUENTIAL_THRESHOLD; i++)
{
counter += subtasks[i].join();
}
return new TrueResult(counter);
}

Categories