calculating fibonacci numbers in java - java

I am trying to display the first 20 fibbonacci numbers using the model view controller method in java. However the output that I am getting is only the last number(the first 19 are not displaying) if anyone is able to look through my code and point out where im going wrong that would be awesome :)
public class FibonacciModel {
public String fibModel(int a, int b, int c, int count){
String result = "";
//int c;
while(count!=20) // if you want first 100 fibonacci numbers then change 20 to 100 accordingly
{
c=a+b;
count++;
result = c + " ";
a=b;
b=c;
}
return result;
}
}
public class FibonacciController {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
int b = 1;
int count = 2;
int c = 0;
FibonacciModel Model = new FibonacciModel();
FibonacciView View = new FibonacciView();
View.say(Model.fibModel(a, b, c, count));
}
}
public class FibonacciView {
public < T > void say( T word ){
System.out.print(word);
}
}

You're overwriting your result variable. Try result = result + c + " "; or result += c + " ";

Check this out :)
public static void getFibbonacci(int n){
int total = 0;
int prev = 1;
for (int x=1; x<n; x++){
total = total + prev;
prev = total - prev;
System.out.println(total);
}
}

public class fibbo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a;
System.out.println("Enter the number");
a = sc.nextInt();
int first = 0;
int second = 1;
int third;
System.out.print("Fibbonacci series is= ");
System.out.print("\t" + first + "\t" + second + "\t");
for (int i = 0; i < a - 2; i++) {
third = first + second;
first = second;
second = third;
System.out.print(third + "\t");
}
}

Related

how to return in a recurssive fn in java

Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}

implementing Subset Sum with genetic Algorithm

import java.util.Collections;
import java.util.Vector;
public class Metaheuristic {
private static int[] DATA;
private static int NUM_CHROMOSOMES ;
private static int MAX_POWER;
private static int MAX_NUMBER;
private static int FITNESS_THRESHOLD;
private static float MUTATE = (float) .05;
private Vector population;
private boolean done = true;
int numRuns = 0;
public void GeneticAlgorithm (int[] data, int target, int n){
NUM_CHROMOSOMES = n;
MAX_POWER = data.length;
MAX_NUMBER = (int) Math.pow(2, MAX_POWER) - 1;
FITNESS_THRESHOLD = target;
DATA = new int[data.length];
DATA = data;
Metaheuristic s = new Metaheuristic();
s.start();
//System.out.println("s");
}
public Metaheuristic(){
generateRandomPopulation();
}
private void generateRandomPopulation(){
System.out.println("***Randomly Generating population with: " + NUM_CHROMOSOMES + " Chromosome(s)***");
population = new Vector();
for(int i = 0; i < NUM_CHROMOSOMES; ++i){
int randomValue = (int) (Math.random()*MAX_NUMBER);
population.add(new Chromosome(randomValue, MAX_POWER));
}
System.out.println("First Population: " + population +"\n");
}
public void start(){
Collections.sort(population);
Chromosome fitess = (Chromosome) population.lastElement();
done = fitess.fitness(DATA, FITNESS_THRESHOLD) >= MAX_POWER? true:false;
if(done){
System.out.println("DONE, solution found: " + fitess);
}
else{
numRuns++;
System.out.println("FITESS: " + fitess + " fitness: " + fitess.fitness(DATA, FITNESS_THRESHOLD ));
generateNewPopulation();
start();
}
}
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Vector temp = new Vector();
for(int i = 0; i < population.size()/2; ++i){
Chromosome p1 = selectParent();
Chromosome p2 = selectParent();
temp.add(cross1(p1, p2));
temp.add(cross2(p1, p2));
}
population.clear();
population.addAll(temp);
System.out.println("New Population: " + population + "\n");
}
private Chromosome selectParent(){
int delta = population.size();
delta = NUM_CHROMOSOMES - NUM_CHROMOSOMES/2;
int num = (int) (Math.random()*10 + 1);
int index;
if(num >= 4){
index = (int) (Math.random()*delta + NUM_CHROMOSOMES/2);
}
else{
index = (int) (Math.random()*delta);
}
return (Chromosome) population.get(index);
}
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS1.substring(0, length/2) + bitS2.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS2.substring(0, length/2) + bitS1.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private boolean shouldMutate(){
double num = Math.random();
int number = (int) (num*100);
num = (double) number/100;
return (num <= MUTATE);
}
private void mutate(Chromosome offspring){
String s = offspring.getBitString();
int num = s.length();
int index = (int) (Math.random()*num);
String newBit = flip(s.substring(index, index+1));
String newBitString = s.substring(0, index) + newBit + s.substring(index+1, s.length());
offspring.setBitString(newBitString);
}
private String flip(String s){
return s.equals("0")? "1":"0";
}
public static void main(String[] args) {
double average = 0;
int sum = 0;
for(int i = 0; i < 10; ++i){
Metaheuristic s = new Metaheuristic();
s.start();
sum = sum + s.numRuns;
average = (double) sum / (double)(i+1);
System.out.println("Number of runs: " + s.numRuns);
}
System.out.println("average runs: " + average);
}
}
import java.lang.Comparable;
public class Chromosome implements Comparable{
protected String bitString;
public static int[] DATA;
public int TARGET;
public Chromosome(){
}
public Chromosome(int value, int length){
bitString = convertIntToBitString(value, length);
}
public void setBitString(String s){
bitString = s;
}
public String getBitString(){
return bitString;
}
public int compareTo(Object o) {
Chromosome c = (Chromosome) o;
int num = countOnes(this.bitString) - countOnes(c.getBitString());
return num;
}
public int fitness(int[] data, int target){
DATA = new int[data.length];
System.arraycopy(data, 0, DATA, 0, data.length);
TARGET = target;
return countOnes(bitString);
}
public boolean equals(Object o){
if(o instanceof Chromosome){
Chromosome c = (Chromosome) o;
return c.getBitString().equals(bitString);
}
return false;
}
public int hashCode(){
return bitString.hashCode();
}
public String toString(){
return "Chromosome: " + bitString;
}
public static int countOnes(String bits){
int sum = 0;
for(int i = 0; i < bits.length(); ++ i){
String test = bits.substring(i, i+1);
sum = sum + (DATA[i]*Integer.parseInt(test));
}
return sum;
}
public static String convertIntToBitString(int val, int length){
int reval = val;
StringBuffer bitString = new StringBuffer(length);
for(int i = length-1; i >=0; --i ){
if( reval - (Math.pow(2, i)) >= 0 ){
bitString.append("1");
reval = (int) (reval - Math.pow(2, i));
}
else{
bitString.append("0");
}
}
return bitString.toString();
}
/* public static void main(String[] args){
//System.out.println(convertIntToBitString(2046, 10));
Chromosome c = new Chromosome(1234, 10);
System.out.println(c.fitness());
}*/
}
My fitness function is f(x ) = s · (C − P(x )) + (1 − s) · P(x ) in which C is my target value to reach and P(*x ) = (Sigma) wixi, where wi is the element's set and xi is 0 or 1 (the element is chosen or not). also s is 0 or 1, depends on p(x) value. please help me to write this fitness.
I have just tried it but the program run with errors.
You have several problems in your code, and obviously you didn't debug it. Here are some tips though.
First NUM_CHROMOSOMES is 0, because it's an uninitialized field (of the GeneticAlgorithm which you don't use).
Since NUM_CHROMOSOMES is 0, this for loop is useless:
for (int i = 0; i < NUM_CHROMOSOMES; ++i) {
Then, this line:
int randomValue = (int) (Math.random() * MAX_NUMBER);
Since MAX_NUMBER is never manually initialized (same as NUM_CHROMOSOMES, its value is 0, and so is randomValue.
Anyway, population is empty and since you don't test for emptyness, this line:
Chromosome fitess = (Chromosome) population.lastElement();
... throws an exception, because there is no such thing as a last element in your empty population Vector.
As a side note, StringBuffer, Vector are obsolete classes, and you never need to import Comparable, since it belongs to the java.lang package.

Sum of columns and rows of 2D array

I've searched up and down for the fix to my issue, but none seem to work. One particular reference-- this and this, and especially this. However, no matter how I implement them, I receive an OutOfBoundsError, which I can't understand.
The program is extra credit for a class. In truth, it is very simple--
Program Description: Use a two dimensional array to solve the following problem. A company has four sales persons (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each different type of product sold. Each slip contains:
The sales persons numberThe product numberThe total dollar value of that product sold that day
Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume that the information from all of the slips for last month is available. Each data line contains 3 numbers (the sales person number, product number, sales).
Write a program that will read all this information for last month’s sales, and summarize the total sales by salesperson by product.
The data provided:
1 2 121.77
1 4 253.66
1 5 184.22
1 1 97.55
2 1 152.44
2 2 104.53
2 4 189.97
2 5 247.88
3 5 235.87
3 4 301.33
3 3 122.15
3 2 301.00
3 1 97.55
4 1 125.66
4 2 315.88
4 4 200.10
4 3 231.45
The error only comes when it tries to calculate the columns. My rows work; no matter how I change the for-loop or any of the indeces in the row or column of the array, it doesn't work. I at first had my rows calculated separately, then my column sums, and it didn't work either. There is something that I'm missing that I'm clearly overlooking.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class prog480u {
static Scanner inFile = null;
public static void main(String[] args) {
try {
// create scanner to read file
inFile = new Scanner(new File ("prog480u.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
// make the array
int x = 0;
int y = 0;
double[][] profits = new double[4][5];
while (inFile.hasNext()) {
x = inFile.nextInt(); // use sales numbers as coordinates
y = inFile.nextInt();
profits[x - 1][y - 1] = inFile.nextDouble();
}
// check if it's okay
System.out.println("");
double[][] columnProfits = sums(profits);
for (int a = 0; a < columnProfits.length; a++) {
System.out.print((a+1) + "\t");
for (int b = 0; b < columnProfits[a].length; b++) {
System.out.print(columnProfits[a][b] + "\t");
}
System.out.println("");
}
double[] bottomRow = columnSums(columnProfits);
for (int a = 0; a < bottomRow.length; a++) {
System.out.print("Total:" + bottomRow + "\t");
}
}
public static double[][] sums (double[][] q) {
double[][] array = new double[5][6];
array = q;
double sum = 0;
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum += array[a][b]; // add everything in the row
}
array[a][4] = sum; // set that row to the last column
sum = 0; // reset sum to 0
}
return array;
}
public static double[] columnSums (double[][]q) {
double[][] array = new double[5][6];
array = q;
double sum2 = 0;
double[] columns = new double [5];
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum2 += array[b][a];
columns[b] = sum2;
}
sum2 = 0; // reset sum to 0
}
return columns;
}
}
Thank you very much for your time. I have a feeling my program is close to working, but this small mistake is pushing me over the edge.
Here's the working code (I cleaned it up a bit):
You were very close, you just needed to swap your max indicies in the for loops. That's why you were getting a java.lang.ArrayIndexOutOfBoundsException
public static double[] columnSums(double[][] q)
{
double[][] array = q;
double[] columns = new double[5];
for (int a = 0; a < array[0].length; a++)
{
for (int b = 0; b < array.length; b++)
{
columns[a] += array[b][a];
}
}
return columns;
}
Just for fun, I wrote the object oriented version for that.
Easier to handle once the system requires additional functionalities:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
class Sale {
static public ArrayList<Sale> readSales(final String pSalesFileName) throws FileNotFoundException, IOException {
final ArrayList<Sale> ret = new ArrayList<>();
try (final BufferedReader br = new BufferedReader(new FileReader(pSalesFileName))) {
int lineIndex = 0;
while (true) {
++lineIndex;
final String line = br.readLine();
if (line == null) {
System.out.println("Line #" + lineIndex + " is empty, skipping...");
break;
}
try {
final String[] values = line.split("\\s");
final int salesPersonId = Integer.parseInt(values[0]);
final int productId = Integer.parseInt(values[1]);
final float sales = Float.parseFloat(values[2]);
final Sale sale = new Sale(salesPersonId, productId, sales);
ret.add(sale);
} catch (final ArrayIndexOutOfBoundsException e) {
System.err.println("Parse error in line #" + lineIndex + ": '" + line + "'");
}
}
}
return ret;
}
private final int mSalesPersonId;
private final int mProductId;
private final float mSales;
public Sale(final int pSalesPersonId, final int pProductId, final float pSales) {
mSalesPersonId = pSalesPersonId;
mProductId = pProductId;
mSales = pSales;
}
public Integer getSalesPersonId_R() {
return Integer.valueOf(mSalesPersonId);
}
public Integer getProductId_R() {
return Integer.valueOf(mProductId);
}
public float getSales() {
return mSales;
}
}
class SalesPerson {
private final HashMap<Integer, ArrayList<Sale>> mSalesMap = new HashMap<>();
private final int mId;
public SalesPerson(final int pId) {
mId = pId;
}
#Override public boolean equals(final Object pObj) {
if (!(pObj instanceof SalesPerson)) return false;
return ((SalesPerson) pObj).mId == mId;
}
#Override public int hashCode() {
return mId;
}
public void addSale(final Sale pSale) {
final Integer productId = pSale.getProductId_R();
ArrayList<Sale> salesList = mSalesMap.get(productId);
if (salesList == null) {
salesList = new ArrayList<>();
mSalesMap.put(productId, salesList);
}
salesList.add(pSale);
}
public Integer getId_R() {
return Integer.valueOf(mId);
}
public HashMap<Integer, ArrayList<Sale>> getSalesMap() {
return mSalesMap;
}
public float getSalesTotalByProductId(final Integer pProductId) {
final ArrayList<Sale> sales = mSalesMap.get(pProductId);
float accumulator = 0;
for (final Sale sale : sales) {
accumulator += sale.getSales();
}
return accumulator;
}
}
public class SalesFun {
public static void main(final String[] args) throws FileNotFoundException, IOException {
final ArrayList<Sale> sales = Sale.readSales("test/sales.txt");
final HashMap<Integer, SalesPerson> personMap = new HashMap<>();
for (final Sale sale : sales) {
// find right salesperson or create new, then add sale to it
final Integer salesPersonId = sale.getSalesPersonId_R();
SalesPerson person = personMap.get(salesPersonId);
if (person == null) {
person = new SalesPerson(salesPersonId.intValue());
personMap.put(salesPersonId, person);
}
person.addSale(sale);
}
printSales(personMap);
}
static private void printSales(final HashMap<Integer, SalesPerson> pPersonMap) {
for (final SalesPerson person : pPersonMap.values()) {
System.out.println("SalesMan ID: " + person.getId_R());
for (final Entry<Integer, ArrayList<Sale>> entry : person.getSalesMap().entrySet()) {
final Integer productId = entry.getKey();
final float sales = person.getSalesTotalByProductId(productId);
System.out.println("\tProduct ID: " + entry.getKey() + "\tSales: " + sales);
}
}
}
}

Calculator, can't get it to print out as I want it

This is a homework of mine. However, I can't get the result to work. I want it to print out as:
> 2*7*6
2
* 7
----
14
* 6
----
84
and so on. I want the code to work regardless of how many numbers I type in. This is my code so far;
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("(ex. 8*2*6): ");
String amount = in.nextLine();
if ( amount.contains("+") ) {
String[] parts = amount.split("\\+");
} else if ( amount.contains("-") ) {
String[] parts = amount.split("\\-");
} else if ( amount.contains("*") ) {
String[] parts = amount.split("\\*");
int[] results = new int[parts.length];
// Convert from string to integer
for (int i = 0; i < parts.length; i++) {
try {
results[i] = Integer.parseInt(parts[i]);
} catch (NumberFormatException nfe) {};
}
// Print result
int counter = 1;
for (int i = 0; i <= results.length; i++) {
if ( i == 0) {
System.out.println(" " + results[i]);
System.out.println("* " + results[counter]);
System.out.println("----");
int total = multiply(results[i], results[counter]);
System.out.println(" " + total);
} else if ( i > 1 ) {
System.out.println("* " + results[i]);
System.out.println("----");
System.out.println(" " + multiply(results[i], results[counter]) );
}
}
} else {
System.out.println("Error");
}
What am I doing wrong?
Is not c# isn it? I'm not sure if i understand you.
In c#, have you tried something like that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args) {
// Scanner in = new Scanner(System.in);
// String amount = Console.ReadLine();
String amount = "2*7*6*5*3*2";
if (amount.Contains('+')) {
String[] parts = amount.Split('+');
}
else
if (amount.Contains('-')) {
String[] parts = amount.Split('-');
}
else if (amount.Contains("*")) {
String[] parts = amount.Split('*');
int[] results = new int[parts.Length];
// Convert from string to integer
for (int i = 0; i < parts.Length; i++) {
try {
results[i] = int.Parse(parts[i]);
}
catch (FormatException nfe) { };
}
// Print result
int total = results[0];
for (int i = 1; i < results.Length; i++) {
if (i == 1)
Console.WriteLine(" " + results[i - 1]);
Console.WriteLine("* " + results[i]);
Console.WriteLine("----");
total = multiply(results[i], total);
Console.WriteLine(" " + total);
}
}
else {
Console.WriteLine("Error");
}
Console.ReadKey();
}
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
}
}
}

How do I call a private method with arguments

I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.
main class:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
//this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for(int n = 1; n <= max; n++)
{
for(a = n; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
String last = a + "" + b + c;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = output + this.greatestCommonFactor( ) + " \n";
return output;
}
}
and for cross-referencing my runner class:
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples triple = new Triples(big);
//call the toString method to print the triangle
out.println( triple );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
as they are only required within the scope of the method.
Well, yeah. You're not passing anything to greatestCommonFactor. I'm not sure what you expected to happen in your toString() method when you didn't pass enough arguments to a method.
you need to pass them like
output = output + this.greatestCommonFactor(1,2,3) + " \n";
the thing is, unless you are passing parameters to toString, without this, this code seems very limited. Alternatively you need to set some fields on the class with what will be passed into your function.

Categories