Problem Statement:
While playing an RPG game, you were assigned to complete one of the hardest quests in this game. There are n monsters you'll need to defeat in this quest. Each monster i is described with two integer numbers - poweri and bonusi. To defeat this monster, you'll need at least poweri experience points. If you try fighting this monster without having enough experience points, you lose immediately.
You will also gain bonusi experience points if you defeat this monster. You can defeat monsters in any order. The quest turned out to be very hard - you try to defeat the monsters but keep losing repeatedly. Your friend told you that this quest is impossible to complete. Knowing that, you're interested, what is the maximum possible number of monsters you can defeat?
Input:
The first line contains an integer, n, denoting the number of monsters.
The next line contains an integer, e, denoting your initial experience.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, poweri, which
represents power of the corresponding monster.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, bonusi, which represents bonus for defeating the corresponding monster.
Sample cases:
Input 2 123 78 130 10 0
Output 2
Output description
Initial experience level is 123 points.
Defeat the first monster having power of 78 and bonus of 10. Experience level is now 123+10=133.
Defeat the second monster.
What I have tried:
public static int defeat(int [] monster,int bonus[],int n,int exp){
if(n==0)
return 0;
if(n==1 && monster[0]<=exp)return 1;
if(n==1 && monster[0]>exp) return 0;
if(monster[n-1]<=exp){
return defeat(monster,bonus,n-1,bonus[n-1]+exp )+ defeat(monster,bonus,n-1,exp);
}else{
return defeat(monster,bonus,n-1,exp);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
System.out.println(defeat(monst,bonus,n,exp));
}
I am not getting correct answers with this solution.
I thought of this problem as 0/1 knapsack problem( correct me If I am wrong). Also can you provide me DP solution of this problem.
You can just sort the monsters from lowest to highest power required and defeat them in that order.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
class Monster {
private final int power, bonus;
public Monster(int power, int bonus){
this.power = power;
this.bonus = bonus;
}
}
Monster[] monsters = new Monster[n];
for(int i = 0; i < n; i++) monsters[i] = new Monster(monst[i], bonus[i]);
Arrays.sort(monsters, Comparator.comparingInt(m -> m.power));
int count = 0;
for(Monster m: monsters){
if(exp < m.power) break;
exp += m.bonus;
++count;
}
System.out.println(count);
}
Perhaps I am too simplistic, but I would try it as below:
First create a class Monster like this:
public class Monster
{
final int m_Power;
final int m_Bonus;
public Monster( final int power, final int bonus )
{
m_Power = power;
m_Bonus = bonus;
}
public final int getPower() { return m_Power; }
public final int getBonus() { return m_Bonus; }
}
Next, initialise a list of Monsters like this:
public static void main( String... args )
{
final var scanner = new Scanner( System.in );
final var n = scanner.nextInt();
final var experience = scanner.nextInt();
final var power [] = new int [n];
for( var i = 0; i < n; ++i )
{
power [i] = scanner.nextInt();
}
List<Monster> monsters = new ArrayList<>( n );
for( var i = 0; i < n; ++i )
{
monsters.add( new Monster( power [i], scanner.nextInt();
}
monsters.sort( (m1,m2) ->
{
final var p = m1.getPower() - m2.getPower();
return p == 0 ? m2.getBonus() - m1.getBonus(() : p;
} ); //*1
System.out.println( defeat( monsters, experience ) );
}
*1 -> this implementation of the comparator works well only for power and bonus values that are small compared to MAX_INT.
The list monsters now contains the monsters sorted by their power in ascending order; monsters with the same power are ordered by their bonus values in descending order.
Now my implementation of defeat() would look like this:
public final int defeat( final List<Monster> m, final int initialExperience )
{
var experience = initialExperience;
var retValue = 0;
final Stack<Monster> monsters = new LinkedList<>( m );
while( !monsters.empty() )
{
var monster = monsters.pop();
if( experience > monster.getPower() )
{
experience += monster.getBonus();
++retValue;
}
else break;
}
return retValue;
}
n=int(input())
e=int(input())
P=[]
for i in range(n):
P.append(int(input()))
B=[]
for i in range(n):
B.append(int(input()))
c=0
f=True
while n>0 and f:
f=False
i=0
while i<n:
if e>=P[i]:
e+=B[i]
P.pop(i)
B.pop(i)
n-=1
c+=1
f=True
i-=1
i+=1
print(c)
import java.io.*;
import java.util.*;
class Player {
int exp;
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
}
class Monster {
int power;
int bonus;
public int getPower() {
return this.power;
}
public int getBonus() {
return this.bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
public void setPower(int power) {
this.power = power;
}
}
class Calc {
public int calc() {
Scanner sc = new Scanner(System.in);
//number of monsters
System.out.println("enter the number of monsters");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("enter the power of the player");
Player player = new Player();
player.setExp(sc.nextInt());
//declaration of array type object of monster
Monster monster[] = new Monster[n];
//value setting completed
for (int i = 0; i < n; i++) {
//allocation of object to the real
monster[i] = new Monster();
System.out.println("enter the power of monster");
monster[i].setPower(sc.nextInt());
System.out.println("enter the bonus that to be earned after killing the monster");
monster[i].setBonus(sc.nextInt());
}
//calculate win or loose
int count = 0;
int flag = 0;
//**
for (int i = 0; i < n; i++) {
if (player.getExp() >= monster[i].getPower()) {
player.setExp(player.getExp() + monster[i].getBonus());
count = count + 1;
// flag = flag + 1;
} else if (player.getExp() < monster[i].getPower()) {
for (int j = 0; j < n; j++)
arr[j] = i;
//count = count;
flag = flag + 1;
}
//**
for (int t = 0; t < flag; t++) {
if (player.getExp() >= monster[arr[t]].getPower()) {
count = count + 1;
}
}
}
return count;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("welcome to the loosing game");
Calc c = new Calc();
System.out.println("no of monster killed" + c.calc());
}
}
#include<bits/stdc++.h>
using namespace std;
struct Monsters
{
int power;
int bonus;
};
class Solution
{
public:
//Function to find the maximum number of activities that can
//be performed by a single person.
static bool compare(Monsters a, Monsters b)
{
if(a.power < b.power) return 1;
else if(a.power > b.power) return 0;
else return 1;
}
int MonstersKill(vector<int> power, vector<int> bonus, int n, int exp)
{
Monsters arr[n];
for(int i = 0; i < n; i++)
{
arr[i].power = power[i];
arr[i].bonus = bonus[i];
}
sort(arr, arr+n, compare);
int count = 0;
for(int i = 0; i < n; i++)
{
if(arr[i].power <= exp)
{
count++;
exp += arr[i].bonus;
}
else
break;
}
return count;
}
};
int main()
{
int n, exp;
cin >> n >> exp;
vector<int> power(n), bonus(n);
//adding elements to arrays power and bonus
for(int i=0;i<n;i++)
cin>>power[i];
for(int i=0;i<n;i++)
cin>>bonus[i];
Solution ob;
cout << ob.MonstersKill(power, bonus, n, exp) << endl;
return 0;
}
Time Complexity : O(N * Log(N))
Auxilliary Space: O(N)
Related
I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}
I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);
I've been trying to solve this rather easy problem on SPOJ: http://www.spoj.com/problems/HS08PAUL/.
It requires the number of prime numbers (less than n) which can be expressed in the form x^2+y^4 (where x and y are integers) to be found out.
I've whipped up a brute force solution which takes up quite a while for (n ~= 1000000), resulting in a TLE (time limit exceeded) error being thrown by the engine. Here's the source code:
import java.io.*;
import java.util.*;
class HS08PAUL {
public static int[] sieve(int n){
boolean[] prime = new boolean[n+1];
int[] primeNumbers = new int[n];
int index = 0;
Arrays.fill(primeNumbers, 0);
Arrays.fill(prime,true);
prime[0] = false;
prime[1] = false;
int m = (int)Math.sqrt(n);
for(int i = 2; i <= m; i++){
if(prime[i])
for(int k = i*i; k<=n; k+=i)
prime[k] = false;
}
for(int j = 2; j <= n; j++) {
if(prime[j]) {
primeNumbers[index] = j;
index++;
}
}
return primeNumbers;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
double numberOfTestCases = in.nextDouble();
while(numberOfTestCases -- > 0) {
int index = 0, y = 0, count = 0;
int num = in.nextInt();
int[] primes = sieve(num);
while(index < num/3 ) {
for(y = 1; y < 57 ; y ++) {
if(Math.ceil(Math.sqrt(primes[index] - Math.pow(y,4))) == Math.floor(Math.sqrt(primes[index] - Math.pow(y,4)))) {
count++;
break;
}
}
index++;
}
System.out.println(count);
}
}
catch(Exception e) {
}
}
}
Is there a way in which I can make this approach work?
P.S.:Please ignore the unruly exception handling.
How many numbers of the form x^2+y^4 are there below 1000000? How many prime numbers are there below 1000000? What do these two numbers tell you about how you should approach the solution?
#isnot2bad's comment is also relevant.
I just want to know how to limit to number of times a random number appears. I have generated random numbers of 1 to 10 and want to limit each number to appear 4 times.
myArray[i][j] = rand.nextInt(11);
for (int i=0; i < myArray.length; i++) {
for (int j=0; j < myArray[i].length; j++) {
myArray[i][j] = rand.nextInt(11);
System.out.print(" " + myArray[i][j]);
The code above creates the randoms numbers. Just want to limit them.
Since you are limited to 10 * 4 = 40 numbers you can use a list and randomize the index :
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i < 11; ++i) {
for (int j = 0; j < 4; ++j)
numbers.add(i);
}
And then when you assign a random number :
int i = rand.nextInt(numbers.size());
myArray[i][j] = numbers.get(i);
numbers.remove(i);
This assumes your two dimensional will not contain more then 40 numbers
My solution stores the result in arrayList:
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final int range = 10;
int[] numbers = new int[range + 1];
int sum = 0;
final int noOfOccurances = 4;
final int size = range * noOfOccurances;
Arrays.fill(numbers, 0);
Random generator = new Random();
List<Integer> numbersArray = new ArrayList<>();
while (sum != size) {
int randomNumber = generator.nextInt(range) + 1;
if (numbers[randomNumber] != noOfOccurances) {
numbers[randomNumber]++;
sum++;
numbersArray.add(randomNumber);
}
}
System.out.println(numbersArray);
}
}
How about storing the count of the generated int's in an array, or Map, or anything?
Map<Integer, Integer> randomCounts = new HashMap<Integer, Integer>();
... your for loops
myArray[i][j] = rand.nextInt(11);
if (randomCounts.containsKey(myArray[i][j])) {
randomCounts.put(myArray[i][j],randomCounts.get(myArray[i][j])+1);
} else {
randomCounts.put(myArray[i][j],1);
}
And if you want to check them, just iterate through your map, and voilá. :)
You can make a method to check if the generated number exists more than 4 times in the array and create a new random number if it does. It should look like this:
import java.util.Random;
public class rndNumberGenerator {
public static void main (String[] args) {
int[][] myArray = new int[2][5];
Random rand = new Random();
int randomNumber;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
do {
randomNumber = rand.nextInt(11);
} while(overMax(myArray, randomNumber) == true);
myArray[i][j] = randomNumber;
System.out.print(" " + myArray[i][j]);
}
}
}
public static boolean overMax(int[][] array, int number) {
int max = 4;
int count = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
if (array[i][j] == number) {
count++;
}
}
}
if (count >= max)
return true;
else
return false;
}
}
Hope this helped you, if you have any other questions feel free to ask.
I take suggestion by pshemek (vote up): instead the ArrayList, I use the Set because it can't contain duplicate numbers and you have'nt to espicitate control.
An implementation: the copy{right, left} is of pshemek, I had only extended the idea:)
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] numbers = new int[11];
int sum = 0;
final int range = 10;
final int noOfOccurances = 4;
Arrays.fill(numbers, 0);
Random generator = new Random();
Set<Integer> numbersArray = new TreeSet<Integer>();
while (sum != range * noOfOccurances) {
int randomNumber = generator.nextInt(range) + 1;
sum++;//correction for first comment
numbersArray.add(randomNumber); // randomNumber will never be twice: a Set cointains ever one and only one instance of an determinated element
}
System.out.println(numbersArray);
}
}//end class
You could write your own:
public static class CountedRandom {
// My rng.
Random rand = new Random();
// Keeps track of the counts so far.
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
// The limit I must apply.
final int limit;
public CountedRandom(int limit) {
this.limit = limit;
}
public int nextInt(int l) {
int r;
do {
// Keep getting a new number until we hit one that has'n been overused.
r = rand.nextInt(l);
} while (count(r) >= limit);
return r;
}
private int count(int r) {
// How many times have we seen this one so far.
Integer counted = counts.get(r);
if ( counted == null ) {
// Never!
counted = new Integer(0);
}
// Remember the new value.
counts.put(r, counted + 1);
// Returns 0 first time around.
return counted;
}
}
public void test() {
CountedRandom cr = new CountedRandom(4);
for ( int i = 0; i < 50; i++ ) {
System.out.print(cr.nextInt(4)+",");
}
System.out.println();
}
Note that this will hang if you ask for too may numbers in too small a range (as I have in my test).
Prints
2,0,1,2,1,1,3,3,0,3,0,2,2,0,1,3,
and then hangs.
I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}