I am trying to create a program which finds the sum of even numbers below 4 million the Fibonacci sequence. I know there is a much simpler way of doing this, but I wanted to see if it would work with arrays. I have never really used arrays before as I am fairly new to Java, which is why I wanted to see if this worked with arrays. The main problem that I have is with the for statement. How would I see if the contents of fibarray[i] is less than 4000000?
Also, is it OK if I do the thing with the fibarray = new int[i]?
public static void main(String[] args) {
int[] fibarray;
int numcount = 0;
int i = 0;
long sum = 0;
fibarray = new int[i];
fibarray[0] = 0;
fibarray[1] = 1;
for(i = 0 , fibarray[i] < 4000000, i++;;){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
}
I apologise if this sounds really stupid.
Any help would be much appreciated.
Thanks.
Well, you need to start your for loop with i = 2. And the for loop should be in this syntax
for(i = 2; fibarray[i] < 4000000; i++) {
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
See comments within the code:
public static void main(String[] args){
/*************************
* comments on your code
int[] fibarray; //use right java naming convention
int numCount = 0; //this variable is never used
int i = 0;
long sum = 0;
fibarray = new int[i];//you initialize an array of size 0.
fibarray[0] = 0; //you can't set value to array of size 0
fibarray[1] = 1; //you can't set value to array of size 0
//wrong syntax
for(i = 0 , fibarray[i] < 4000000, i++;;){
//use for(i = 0 ; fibarray[i] < 4000000; i++){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
*******************************/
//Alternative code
//you don't need to keep all Fibonachi numbers found.
//you only use 3 numbers for every calculation
int size = 3;
int totalLimit = 4000000;
int[] fibArray = new int[size];
fibArray[0] = 0; fibArray[1] = 1;
int total = 0;
while( true ) {
fibArray[2] = fibArray[0] + fibArray[1] ;
if((fibArray[2]%2) ==0) { //even number
if((total + fibArray[2]) >= totalLimit) {
break;
}
total += fibArray[2];
}
fibArray[0] = fibArray[1] ;
fibArray[1] = fibArray[2] ;
}
System.out.println("Total "+ total );
}
Don't hesitate to ask for clarifications as needed.
Related
I have this code below as I saw from textbook
public static int[][] Pascal(int N) {
int[][] result = new int[N][]; // Build a grid with specific number of rolls
for (int i = 0; i < N; i += 1) {
result[i] = new int[i + 1]; // Build an empty row with length
result[i][0] = result[i][i] = 1;
for (int j = 1; j < i; j += 1) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
}
return result;
}
I have no question for how this Pascal triangle is achieved, all very clear.
However, I did learned before that to create an Array, length must be given,
for example, int[] A = int[]; will give me Error
It has to be int[] A = int[N]; or int[] A = int[]{1,2,3,etc.};
So when we create the array grid int[][] result = new int[N][];
How is it allow me to only specify the number of rows, but leave the length of each row with blank?
I did noticed that the length of each roll was defined later at result[i] = new int[i + 1];, I still don't understand why this grid is allowed to be initiated.
Thanks!
I am creating a histogram using another class to help display it, but that is not important to my question. Let me start by showing my code below
public class DisplayHistogram {
public static void main(String[] args) {
int temp = 0;
int holder = 0;
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
the problem I am having is I set the histogram to have a min of 1 and max of 20. I am generating three random integers and finding the average of the 3 and submitting it to the histogram 10,000 times. However, after the first loop of 10000, the "holder" variable doesn't reset back to 0 causing my program trying to submit a value outside of the max, and creating an error. I have attempted to set holder to 0 at the end of every loop by doing
x.submit(average);
holder = 0;
temp = 0;
However that does not help.
I have tried some of your suggestions making my code look like
import java.util.*;
public class DisplayHistogram {
public static void main(String[] args) {
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
int temp = 0;
int holder = 0;
int average = 0;
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
However it still returns this error
Exception in thread "main" HistogramOutOfBoundsException:
*******
Submitted value 22 is outside range [1,20] of Histogram.
*******
at Histogram.submit(Histogram.java:31)
at DisplayHistogram.main(DisplayHistogram.java:19)
Write your loops like this:
for(int i = 0; i<=10000; i++)
{
holder = 0; // add this line
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
Fixed. Was looping four times instead of three. For loop should've looked like
for(int i=0; i<=2; i++)
Short answer
Pay attention to details.
The answer you want
Unlike the other answer,
don't just initialize the holder variable every loop.
Instead, minimize the scope of the holder variable to the loop.
public static void main(String[] args)
{
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for (final int trialCount = 0; trialCount <= 10000; ++trialCount)
{
int holder = 0;
for (final int sampleCount = 0; sampleCount <= 3; ++sampleCount)
{
int temp = rand.nextInt(20) + 1;
holder += temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
I'm a beginner at java at struggling with this:
I am trying to sum two jagged arrays ( n and m, both double [][]) of the same size (each is length 3 at the first level, then of length x-1,x and x-1 respectively at the second level).
The problem I'm having is to specify the length that each array within the jagged array should be, at the moment my code is producing an n x n array because I've specified the length as n[1] rather than as a parameter, but if I try and use sum[i].length=n[i].length I get the error, "cannot assign value to final variable". So I know this part is wrong but I don't know what is right...
Thanks for the help!
My code:
else if (isValidTridiagonal(m)== true && isValidTridiagonal (n) == true)
{
int size = n[1].length; /** specifying all lengths to be x where they shouldnt be*/
sum = new double[3][size];
for (int i = 0; i < n.length; i++)
{
for(int j = 0; j< n[i].length; j++)
{
sum [i][j]= n[i][j] + m [i][j];
}
}
return sum;
}
There is some missing information. As far as I can tell there are two things you need to fix. You seem to have "sum" as a final variable already defined in your code.
Secondly, you are declaring a new array that is 3xsize big. If you want a jagged array in that sence, you must leave one of the brackets empty and in the first loop insert a new array of the wanted size.
double[][] sum = new double[3][]; //Make sure this is unique within the scope
for(int i = 0; i < 3; i++) { //if you want dynamic scaling you'll need to replace 3 in the array as well.
int size = n[i].length; //size of the new row
sum[i] = new double[size]; // Inserting a new array of the wanted size
for(int j = 0; j< sum[i].length; j++)
{
sum[i][j]= n[i][j] + m[i][j];
}
}
return sum;
The problem is probably with this line:
sum = new double[3][size];
Here you create an incorrect, non-jagged array of size [3][2]
When you try to set sum[1][2] (2nd, 3rd index), you will not be able to.
Otherwise, the code looks correct and I got a sum to work using this:
public static void main(String[] args) {
int[][] n = new int[3][];
n[0] = new int[2];
n[0][0] = 1;
n[1] = new int[3];
n[2] = new int[2];
int[][] m = new int[3][];
m[0] = new int[2];
m[1] = new int[3];
m[1][2] = 1;
m[2] = new int[2];
int[][] sum = new int[3][];
sum[0] = new int[2];
sum[1] = new int[3];
sum[2] = new int[2];
for (int i = 0; i < n.length; i++) { // n.length will be 3
for (int j = 0; j < n[i].length; j++) { // n[i].length will be 2, 3 and 2
sum[i][j] = n[i][j] + m[i][j];
}
}
System.out.println("Sum: ");
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[i].length; j++) {
System.out.print(sum[i][j] + "|");
}
System.out.println();
}
}
This will print off:
Sum:
1|0|
0|0|1|
0|0|
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have this extremely simple program to reverse an array of integers but every time I try to run it, it just ignores the second loop where the reverse should happen and passes it or there maybe some trouble in it.
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
System.out.println("[%" + i + "]=");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
it does not ignore the second loop, it simply should be
for (int i = 0; i < arr.length/2; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
beacuse if you iterate from 0 to arr.length it will reverse Your array twice which in the end gives You back original array,
Just change arr.length to arr.length/2. Now you are reversing it twice.
You should browse your array until his half for not reversing twice ( -- => +).
Always try to use the array size to the browse.
for (int i = 0; i < arr.length; i++)
and not
for (int i = 0; i < 10; i++)
It's more general and correct. You can add a variable to save the array size.
So your code will:
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int arrayLenght = 10;
int[] arr = new int[arrayLenght];
for (int i = 0; i < arrayLenght; i++) {
System.out.print("%[" + i + "]= ");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arrayLenght / 2; i++) {
int temp = arr[i];
arr[i] = arr[arrayLenght - 1 - i];
arr[arrayLenght - 1 - i] = temp;
}
for (int i = 0; i < arrayLenght; i++) {
System.out.println(arr[i]);
}
}
}
I see that others gave you the solution as i'm writing.
Let me give you some suggestions:
-whatever you are trying, magane to keep the developing loop (error, modification, trial and again from start) as short as possible.
-insert data by hand rarely is a good option
so, in this case: better to avoid the first loop and put something like:int [] arr ={5,6,7,8,8,1,8,9,1,9};
-when in doubt fill the code with print so you can follow what the algorithm is doing,the next step will be learn to use the debugger but the first is the print instructions
-if you want to learn, try hard enough (it depends by you) before ask other's people help
Here is the problem
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
You make twice array elements swap
Instead, use
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
The output should look like this:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
Thanks for looking.
No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}
Just print the for variables (i...p) without accessing this obscure empty array.
Well, if it's OK to use some built-in classes, you can do this in the following way:
for (int i=0; i<256; i++){
System.out.println(Integer.toBinaryString(i));
}
And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):
for (int i=0;i<256;i++){
int mask = 256;
while (mask > 0){
if ((mask & i) == 0){
System.out.print("0");
} else {
System.out.print("1");
}
mask = mask >> 1;
}
System.out.println();
}
Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:
public static void printBin()
{
for (int i = 0; i < 256; i++) {
int binary = decToBin(i, "");
// pad to give length of 8
System.out.println(String.format("%08d", binary));
}
}
public static int decToBin(int dec, String bin)
{
int quot = dec / 2;
int remainder = dec % 2;
if (quot == 0)
return Integer.parseInt("" + remainder + bin);
return decToBin(quot, "" + remainder + bin);
}
Heres another way of generating all the values using bit operations
public static void main(String[] args) {
int numBits = 8;
int val = 0;
int[] values = new int[]{0,1};
values[0] = 0;
values[1] = 1;
for (int i = 1; i < numBits; i++) {
int[] moreValues = new int[values.length * 2];
int start = (int)Math.pow(2, i);
for (int j = 0; j < values.length; j++) {
moreValues[j * 2] = values[j] << 1;
moreValues[j * 2 + 1] = values[j] << 1 | 1;
}
values = moreValues;
}
//print the values
for (int value: values) {
System.out.println(Integer.toBinaryString(value));
}
}
And another way, using bit operations and recursion
private static void generateNumbers(int number, int numBits, int currentBit) {
if (numBits == currentBit) {
Integer.toBinaryString(number);
return;
}
currentBit++;
generateNumbers(number << 1, numBits, currentBit);
generateNumbers(number << 1 | 1, numBits, currentBit);
}
public static void generateNumbers(int numBits) {
generateNumbers(0, 8, 1);
generateNumbers(1, 8, 1);
}
public static void main(String[] args) {
generateNumbers(8);
}
package org.cross.topology;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//System.out.println("sushil");
int digits=3;//Provide number of digits for which you want combinations of 0 and 1
int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
String current_char="0";
int startindex=0,lastindex;
ArrayList<String> al=new ArrayList<String>(combinations);
for(int k=0;k<combinations;k++)
{
al.add("");
}
for(int i=1;i<=digits;i++)
{
noof0and1=noof0and1/2;
while(temp!=combinations)
{
temp=temp+noof0and1;
secondloopcounter++;
}
lastindex=noof0and1;
startindex=0;
for(int s=0;s<secondloopcounter;s++)
{
for(int j=startindex;j<lastindex;j++)
{
String temps=al.get(j)+current_char;
al.remove(j);
al.add(j, temps);
}
if(current_char.equals("0"))
{
current_char="1";
}
else
{
current_char="0";
}
startindex=lastindex;
lastindex=lastindex+noof0and1;
}
temp=0;
secondloopcounter=0;
}
for(int l=0;l<al.size();l++)
{
System.out.println(al.get(l));
}
}
}
Below is the solution using Recursion as an approach in java
public class NumberOfBinaryPatterns {
static int[] bitArray = new int[]{0,1};
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int numberOfBits=4; // It can be any value based on the requirement, In this case we can put this as 8
drawBinaryPattern(numberOfBits,"");
}
private static void drawBinaryPattern(int n,String seed)
{
if(n==0){
System.out.println(seed);
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
drawBinaryPattern(n-1,temp);
}
}
}
Do in php , very easy
Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.
for($c=1;$c<=pow(2,8);$c++)
{
$bin_str=base_convert($c,10,2); //converting combination number into binary string
$len_str=strlen($bin_str); // Length of string obtained
for($i=1;$i<=8-$len_str;$i++)
$bin_str="0".$bin_str; // adding as many 0 as required to complete in byte format
echo "<br>".$bin_str; //Displaying binary values in byte structure
}