I am working on an assignment to create a bar graph using Java using random numbers, but I do not know how to code it properly, it keeps on giving errors when I move on to the next step.
public class BinSort {
final int N_BINS = 0; //number of bins
final int N_SAMPLES = 0; //total random integers
final float BIN_WIDTH = 0; //width of the bin
int [] nums; //generate and store random numbers
int [] binCount; //array
int max = 0; //largest random number = (max-1)
public void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
This code is incomplete, but I do not know what to do next. So, I am stuck.
Can someone please help me?
Edit: The program does not compile after running in eclipse. It says the execution is terminated in the console.
Only static variables can be used in the static method . Below code is compiling fine:
public class BinSort {
static final int N_BINS = 0; //number of bins
static final int N_SAMPLES = 0; //total random integers
static float BIN_WIDTH = 0; //width of the bin
static int [] nums; //generate and store random numbers
int [] binCount; //array
static int max = 0; //largest random number = (max-1)
public static void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
The time-limit-extended is the status when executing the successfully compiled class file of the following code.
import java.io.*;
public class CandidateCode {
public static int ThirstyCrowProblem(int[] input1, int input2, int input3) {
int[] arrK = new int[input3];
int minstones = 0;
for (int i = 0; i < input3; i++) //create an array of k Os.
{
int smallest = input1[0], place = 0;
for (int j = 0; j < input2; j++) {
if ((smallest >= input1[j]) && (input1[j] >= 0)) {
smallest = input1[j];
place = j;
}
}
input1[place] = -1;
arrK[i] = smallest;
}
int n = input2, i = 0;
while (i < input3)
minstones = minstones + arrK[i] * (n - i);
return minstones;
}
public static void main(String[] args) {
int[] arr = new int[] {
5, 58
};
int stones_min = CandidateCode.ThirstyCrowProblem(arr, 2, 1);
System.out.println("The result is" + stones_min);
}
}
The cursor is waiting and waiting, but I don't think there is an error in the code!??
Option A :
Change your while into an if statement :
if(i<input3) {
minstones= minstones + arrK[i]*(n-i);
}
Option B : or increment i (i++) but I don't this that's what you want
while(i<input3) {
minstones = minstones + arrK[i]*(n-i);
i++;
}
You need to increment i in your while loop.Since you are not incrementing,its going in infinite loop.
while(i<input3)
{
minstones= minstones + arrK[i]*(n-i);
i++;
}
After making this change,I got
The result is10
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 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;
}
}
}
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}
This is what am producing so far:
6
3 5
9 7 1
4 6 8 4
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
Any help would be appreciated!
Here, just change with your solve()
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
#Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
Try
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
Simple-Solution:
1.Add the static list as here:
private static List maxRowVal=new ArrayList();
2.Replace your generateTriangle() function with this:
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
Simple indeed!!
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
Output:
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.