Pick 4 Cards Homework - java

Note: This has been solved. I have posted the working code below in a later post.
First off, I know there is a similar question here: Pick four cards and compute their sum JAVA
However, the outcome of their script is different than what mine needs to be, they are just calculating 4 random cards. I need to find EVERY combination of 4 cards that exists.
I am currently in my first Java programming class. We have covered up to methods and arrays, but nothing about classes and objects yet. So please keep that in mind if you choose to answer.
My homework this week is to write a program that finds every possible combination of 4 cards in a deck of 52 that add up to 24. (with Ace being 1, Jack 11, Queen 12, and King 13) I have posted my code below which I know has some mistakes, it doesn't work right for how I want it to. I am posting here to see if I'm on the right track. My instructor says the correct answer is 12,517, and it's up to us to come up with that answer. Any hints would be greatly appreciated.
Specific Question as requested - "How can I change my below code that will produce the output of 12,517"
Things I know:
I know some numbers are missing in the iterations, the 4th stack resets back to 4 instead of going to 1. I haven't yet figured out how to correct this.
I know my deepest For loop will loop the same combination 4 times before continuing... I have NO idea why (or how) it's doing this.
NOTE!: I have output messages in the "calculate" method for debugging. If you want to use them, start then stop the script immediately, that will give you an idea. If you want the program to run till completion, then comment out the 3 output messages in the nested 4 loop.
public static void main(String[] args) {
int[] deck = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int total;
total = calculate(deck);
output(total);
}
public static int calculate(int[] deck){
int total = 0;
int stack1, stack2, stack3, stack4, accumulate;
for (stack1 = 0; stack1 < 52; stack1++){
for (stack2 = 1; stack2 < 52; stack2++){
for (stack3 = 2; stack3 < 52; stack3++){
for (stack4 = 3; stack4 < 52; stack4++){
accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
System.out.println(deck[stack1] + " + " + deck[stack2] + " + " + deck[stack3] + " + " + deck[stack4]);
if (accumulate == 24){
System.out.println(deck[stack1] + " + " + deck[stack2] + " + " + deck[stack3] + " + " + deck[stack4]);
total++;
System.out.println("Accumulate is at " + accumulate);
System.out.println("Currently at " + total);
}
}
}
}
}
return total;
}
public static void output(int total){
System.out.println ("The total number of card combinations of 4 that \n"
+ "equal 24 is: " + total);
}
}

I would do it as such:
public static void main(String[] args) {
int counter = 0; //can also just say int counter; ==> auto intialize to 0
int d, c, h, s; //diamond, club, heart, spade
for(d = 1; d < 14; d++) //each suit starts at Ace, or the value of 1
for(c = 1; c < 14; c++) //each suit ends at 13, or King
for(h = 1; h < 14; h++)
for(s = 1; s < 14; s++)
if( d + c + h + s == 24 )
counter++;
System.out.println(counter); //Your total should be your instructor's 12,517
}
If I may clarify your question: You do NOT mean to ask for every single "combination" of cards (so printing out all 12,517 possibilities).
Rather, you mean to get the total number of combinations represented by counter.
What my four for loops are doing is very simple: it goes through all the possibilities using Ace as 1 and King as 13. If the sum of the four cards equals ( == ) 24, then add one to the counter.
This will work due to the nature of nested for loops, going through all four sets of 13C1 combinatorics.
I hope this helped!
NOTE: In case you weren't aware: in languages with brackets (Java, C), if you're using a conditional statement or a loop (if/else, while, for) with only one following statement, like in my code, you can omit the brackets.

Here is working code that produces the correct result. The key was to parent the child stack to the parent stack + 1:
public static void main(String[] args) {
int[] deck = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int total;
total = calculate(deck);
output(total);
}
public static int calculate(int[] deck){
int total = 0;
int stack1, stack2, stack3, stack4, accumulate;
for (stack1 = 0; stack1 < 52; stack1++){
for (stack2 = (stack1 + 1); stack2 < 52; stack2++){
for (stack3 = (stack2 + 1); stack3 < 52; stack3++){
for (stack4 = (stack3 + 1); stack4 < 52; stack4++){
accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
if (accumulate == 24)
total++;
}
}
}
}
return total;
}
public static void output(int total){
System.out.println ("The total number of card combinations of 4 that \n"
+ "equal 24 is: " + total);
}
}

Related

All possible combinations out of 2 Arrays

I have 2 Arrays:
A {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
B {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
I want to make the user be able to input a x number and then the program should print out all possible multiplications that = x.
the multiplication that = x should be made of 2 numbers 1 of array A and the other number from array B. The numbers cannot be the same.
I've been searching and the only thing I think could work is a nested loop.
I am doing this little project in C# but I kindly don't care if it's in Java I understand also Java.
Thanks in advance for the help.
int num_user;
int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
int[] y = new int[9];
Console.WriteLine("Hello please input the number you think could be the solution :) ");
num_user = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < x.Length; a++ )
for (int b = 0; b < y.Length; b++)
if num_user == a*b //and here is where I get lost
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 5; //The number you want the 2 numbers to multiply to
var query =
from x in a
from y in b
where y != x && x * y == target
select new { x, y };
foreach (var pair in query) Console.WriteLine(pair);
a simple nested loop would work for this
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
if (x != y && x*y == your_number) System.out.format("%d * %d = %d\n",x,y,your_number);
}
}
code not tested, but sth like this should work.
you'll have to implement the arrays for yourself :)
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
string input = string.Empty;
int output = 0;
do
{
Console.WriteLine("Enter number: ");
input = /* Console.ReadLine(); */ "8";
} while (!int.TryParse(input, out output));
int[] first = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] second = new int[] {0,1,2,3,4,5,6,7,8,9};
var list = new List<string>();
for (int i = 0; i < first.Length; i++)
for (int j = 0; j < second.Length; j++)
if (first[i] * second[j] == output)
list.Add(first[i] + " x " + second[j] + " = " + output);
foreach (var str in list) {
Console.WriteLine(str);
}
}
}
See a live demonstration here
This code accepts user input (set to "8" for testing purposes) and will loop through the first array items and then loop through the second array.A multiplication is done for each item in the first by each item in the second using this nested loop logic.Hope this helped you in some way.
I would go for the double loop, as a couple of the other answers do.
In case you want to avoid a double loop (for some particular reason), it can be done without it. In Java:
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// not using b
int x = 8;
for (int firstFactor : a) {
if (firstFactor != 0 && x % firstFactor == 0) {
int secondFactor = x / firstFactor;
if (0 <= secondFactor && secondFactor <= 9 && secondFactor != firstFactor) {
System.out.println("" + firstFactor + " * " + secondFactor);
}
}
}
The code above does not work for x equal to 0, you would have to treat this case specially (which you don’t have to in the double loop approach). For x equal to 8 the code prints:
1 * 8
2 * 4
4 * 2
8 * 1
I suggest using Linq while avoiding Cartesian Join (what if A and B are large?):
int[] A = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] B = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int goal = 10;
var result = A
.Where(a => a != 0 && goal % a == 0) // a from A is divider of the goal
.Where(goal / a != a) // a and b can't be the same
.Where(a => B.Contains(goal / a)) // b is in B
.OrderBy(a => a) // let be nice
.Select(a => string.Format("{0} {1}", a, goal / a));
Test
Console.Write(string.Join(Environment.NewLine, result));
Outcome
2 5
5 2
Stress test:
int[] A = Enumerable.Range(0, 1000000).ToArray();
int[] B = Enumerable.Range(0, 1000000).ToArray();
int goal = 2016;
will return within milliseconds
1 2016
2 1008
3 672
4 504
6 336
7 288
8 252
9 224
...
504 4
672 3
1008 2
2016 1

Extract & Delete patterns not functioning entirely with Arraylists

this is my first time asking a question on here so I apologize for any mistakes in terms of form.
I am working on an assignment for AP Computer Science which involves generating a listarray filled with random ints (within a certain range) and then processing them with methods that remove objects which either exceed or are less than a threshold determined earlier in the program. Here is an example of the code I wrote along with the preconditions provided by my teacher.
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return a new List of Integer that contains, in order, all the numbers in
* orig that are >= mid / 2
*/public static ArrayList<Integer> extractUpper(ArrayList<Integer> orig, int mid) {
ArrayList<Integer> myArray = new ArrayList<Integer>();
for(Integer a: orig) {
if (a >= mid/2)
myArray.add(a);
}
return myArray;
}
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return none PostCondition: all numbers less than mid / 2 have been
* removed from orig
*/
public static void deleteUpper(ArrayList<Integer> orig, int mid) {
for(int j = 0; j < orig.size(); j++) {
if (orig.get(j) >= (mid/2))
orig.remove(j);
}
}
To me, this seems like it should work fine, but when I run this:
ic static void main(String[] args) {
//a.
int listLen = 10;
int listMax = 20;
System.out.println("listLen equals " + listLen + " and listMax equals " + listMax);
System.out.println();
//b.
System.out.println("Generating a fixed-length ArrayList of length " + listLen + " with all values >= 0 and < " + listMax);
ArrayList<Integer> Array1 = Main.buildFixedList(listLen, listMax);
System.out.println(Array1);
//c.
System.out.print("The numbers in this ArrayList >= " + listMax/2 + " are: ");
ArrayList<Integer> Array2 = Main.extractUpper(Array1, listMax);
System.out.println(Array2);
//d.
System.out.print("After deleting numbers > " + listMax/2 + " the modified list is: ");
Main.deleteUpper(Array1, listMax);
System.out.println(Array1);
//e.
System.out.print("After deletion, the numbers in the List >= " + listMax/2 + " are: ");
ArrayList<Integer> Array3 = Main.extractUpper(Array1, listMax);
System.out.println(Array3);
//f.
System.out.println();
My output seems to ignore certain numbers, some more frequently than others.
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[14, 16, 12, 9, 8, 11, 14, 16, 1]
The numbers in this ArrayList >= 10 are: [14, 16, 12, 11, 14, 16]
After deleting numbers > 10 the modified list is: [16, 9, 8, 14, 1]
After deletion, the numbers in the List >= 10 are: [16, 14]
The >=10 and <10 methods work occasionally, but I figure it's more of a crap-shoot right now. In this particular example the >=10 method worked but the <10 did not. I am at a loss as to what is wrong with my code.
EDIT:
Thank you for all the replies, I appreciate the help. I have edited both the extractUpper and deleteUpper methods and am getting an even higher rate of success, but the code just seems to ignore some numbers. Here's the code:
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return a new List of Integer that contains, in order, all the numbers in
* orig that are >= mid / 2
*/public static ArrayList<Integer> extractUpper(ArrayList<Integer> orig, int mid) {
ArrayList<Integer> myArray = new ArrayList<Integer>();
for (int i = 0; i < orig.size(); i++){
if(orig.get(i) >= mid/2) {
myArray.add(orig.get(i));
}
}
return myArray;
}
/**
* #param orig is a List of Integer
* #param mid is an int > 2
* #return none PostCondition: all numbers less than mid / 2 have been
* removed from orig
*/
public static void deleteUpper(ArrayList<Integer> orig, int mid) {
for ( int i = orig.size()-1; i >= 0; i--){
if (i < orig.size()) {
if(orig.get(i) >= mid/2) {
orig.remove(i);
i++;
}
}
else
i--;
}
}
Here are a few outputs directly from the program:
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[4, 15, 8, 11, 18, 16, 7, 3, 6]
The numbers in this ArrayList >= 10 are: [15, 11, 18, 16]
After deleting numbers > 10 the modified list is: [4, 8, 7, 3, 6]
After deletion, the numbers in the List >= 10 are: []
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[6, 3, 9, 16, 4, 4, 17, 8, 4]
The numbers in this ArrayList >= 10 are: []
After deleting numbers > 10 the modified list is: [6, 3, 9, 4, 4, 8, 4]
After deletion, the numbers in the List >= 10 are: []
listLen equals 10 and listMax equals 20
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[4, 5, 0, 4, 12, 12, 1, 12, 10]
The numbers in this ArrayList >= 10 are: [12, 12, 12, 10]
After deleting numbers > 10 the modified list is: [4, 5, 0, 4, 1, 12]
After deletion, the numbers in the List >= 10 are: [12]
Generating a fixed-length ArrayList of length 10 with all values >= 0 and < 20
[15, 16, 2, 8, 1, 7, 3, 0, 15]
The numbers in this ArrayList >= 10 are: [12]
After deleting numbers > 10 the modified list is: [2, 8, 1, 7, 3, 0]
After deletion, the numbers in the List >= 10 are: [12]
Your problem is in the function deleteUpper
You should iterate in reverse order the collection to be able to remove item without impacting the original index of the collection
The problem is in the deleteUpper method.
When you delete an item from an List, the indexes in that List change - if you remove item 3, the item that was previously accesible at index 4 now becomes number 3.
In your implementation you always increase the index pointer, regardless if the deletion happened or not. This means that if two consecutive items meet the deletion criterion, only the first one will be removed.
Use an Iterator instead:
Iterator<Integer> i = orig.iterator();
while (i.hasNext()) {
if (i.next() >= mid) {
i.remove();
}
}
If you don't want to use an Iterator:
for (int i=0; i<orig.size(); ) {
if (orig.get(i) >= mid) {
orig.remove(i);
}
else {
i++;
}
}

Find minimum total server downtime

You have an array that represents a line of servers by their "Down-time cost". You can only access servers at either end of the line (i.e You can only get the first server or the last server).
The order at which a server is picked is multiplied with it's downtime and added to a "total downtime cost".
Design a program to find the least total downtime cost.
For example, for the array:
[5, 3, 6, 2, 1, 4]
the least total downtime is:
5*1 + 4*2 + 3*3 + 6*4 + 2*5 + 1*6 = 62
This is the code that I use for getting this result:
public static void main(String[] args){
int[] serverDowntimes = {5, 3, 6, 2, 1, 4};
int start = 0;
int end = serverDowntimes.length - 1;
long totalCost = 0;
int serverNumber = 1;
while(start <= end){
if(serverDowntimes[start] >= serverDowntimes[end]){
totalCost += serverNumber * serverDowntimes[start];
start++; //Increment start (i.e. First server in line was recovered)
}else{
totalCost += serverNumber * serverDowntimes[end];
end--; //Decrement end (i.e. Last server in line was recovered)
}
serverNumber++;
}
System.out.println(totalCost);
}
However my code fails when I have this array:
[5, 3, 1, 8, 2, 4]
For this array my code outputs:
76 (5*1 + 4*2 + 3*3 + 2*4 + 8*5 + 1*6)
However the better answer should be:
73 (4*1 + 2*2 + 8*3 + 5*4 + 3*5 + 1*6)
How do I modify my code so that it also works with the arrays similar to:
[5, 3, 1, 8, 2, 4]
I wrote brute-force algorithm that tests every possible solution and picks the best.
For following problem set:
[5, 3, 1, 8, 2, 4]
It generates solution of:
lowest cost: 72, with combination: [5, 4, 2, 8, 3, 1]
Which we can prove by calculating:
5*1 + 4*2 + 2*3 + 8*4 + 3*5 + 1*6 = 72
Here's the solver:
import java.util.*;
class ServersProblemSolver {
public static void main(String[] args) {
int[] serverDowntimes = {5, 3, 1, 8, 2, 4};
int totalCost = Integer.MAX_VALUE;
List<Integer> bestCombination = new ArrayList<>();
for (int i = 0; i < Math.pow(2, serverDowntimes.length); i++) {
int temporaryCost = 0;
int combination = i;
int start = 0;
int end = serverDowntimes.length - 1;
List<Integer> temporaryCombination = new ArrayList<>();
for (int k = 0; k < serverDowntimes.length; k++) {
if (combination % 2 == 1) {
temporaryCost += (k + 1) * serverDowntimes[start];
temporaryCombination.add(serverDowntimes[start]);
start++;
} else {
temporaryCost += (k + 1) * serverDowntimes[end];
temporaryCombination.add(serverDowntimes[end]);
end--;
}
combination /= 2;
}
System.out.println("combination " + i + ": " + temporaryCombination + ", cost : " + temporaryCost);
if (temporaryCost < totalCost) {
totalCost = temporaryCost;
bestCombination = temporaryCombination;
} else {
temporaryCombination.clear();
}
}
System.out.println("lowest cost: " + totalCost + ", with combination: " + bestCombination);
}
}
How does it work?
Take every binary combination between 0 and 2 ^ N, where N is the size of your array.
Pick a server from start or end according to succesive binary digit (whether it's 0 or 1)
101 will take start, end, start
000 will take end, end, end
110 will take end, start, start
etc.
After calculating the result of current combination, check if it's better than the previous best, and if so, save it.

Project Euler, problem 2- Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a relatively new java programmer and I've been tinkering around with this program for the better part of the day now and I'm still stuck; I was hoping that you could help me with this.
So the program is supposed to meet the following requirements:
Each new term in the Fibonacci
sequence is generated by adding the
previous two terms. By starting with 1
and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the
Fibonacci sequence whose values do not
exceed four million, find the sum of
the even-valued terms.
This is my code:
//Generates Fibonacci sequence
while (fibNum < 144)
{
int lastValue = (Integer) fibList.get(fibList.size()-1);
int secondToLastValue = (Integer) fibList.get(fibList.size()-2);
fibNum = secondToLastValue + lastValue;
if (fibNum < 144)
{
fibList.add(fibNum);
}
//Picks out the even numbers from limitFibList
for (int i = 0; i < fibList.size(); i++)
{
if ((Integer) fibList.get(i) % 2 == 0)
{
evenNumsFibList.add(fibList.get(i));
}
}
//Sums up the total value of the numbers in the evenNumsFibList
for (int i = 0; i < evenNumsFibList.size(); i++)
{
sum += (Integer) evenNumsFibList.get(i);
}
...and this is the output that I'm getting:
Fibonacci sequence list: [1, 2, 3]
Size of the Fibonacci list: 3
Even Numbers list: [2]
Total sum of even numbers: 2
Fibonacci sequence list: [1, 2, 3, 5]
Size of the Fibonacci list: 4
Even Numbers list: [2, 2]
Total sum of even numbers: 6
Fibonacci sequence list: [1, 2, 3, 5, 8]
Size of the Fibonacci list: 5
Even Numbers list: [2, 2, 2, 8]
Total sum of even numbers: 20
Fibonacci sequence list: [1, 2, 3, 5, 8, 13]
Size of the Fibonacci list: 6
Even Numbers list: [2, 2, 2, 8, 2, 8]
Total sum of even numbers: 44
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21]
Size of the Fibonacci list: 7
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8]
Total sum of even numbers: 78
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34]
Size of the Fibonacci list: 8
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34]
Total sum of even numbers: 156
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55]
Size of the Fibonacci list: 9
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 278
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Size of the Fibonacci list: 10
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 444
Fibonacci sequence list: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Size of the Fibonacci list: 10
Even Numbers list: [2, 2, 2, 8, 2, 8, 2, 8, 2, 8, 34, 2, 8, 34, 2, 8, 34, 2, 8, 34]
Total sum of even numbers: 654
Obviously my while loop is contributing to my problems, but I don't know how to fix it.
Would greatly appreciate your help,
Haque
If you take a closer look at the numbers in the Fibonacci sequence that you actually need (only the even ones need to be summed), you will see a pattern:
0 1 1 2 3 5 8 13 21 34 55 89 144 ...
- O O E O O E O O E O O E
Notice that every 3rd number starting after 0 is even. Therefore, you can eliminate any checking for evenness if you calculate every third Fibonacci number. Looking again at the sequence, you can see that if k is the present even Fibonacci number you are looking at, and j is the one previous, the next even Fibonacci number n can be obtained by:
n = 4k + j
So in Java, you could try something like this:
int j = 0;
int k = 2;
int sum = j+k;
while (k < LIMIT) {
int tmp = 4*k + j;
sum = sum + tmp;
j = k;
k = tmp;
}
Looks like you are missing the close brackets on the while loop. So the other for's are running within it.
So:
while (fibNum < 144)
{
int lastValue = (Integer) fibList.get(fibList.size()-1);
int secondToLastValue = (Integer) fibList.get(fibList.size()-2);
fibNum = secondToLastValue + lastValue;
if (fibNum < 144)
{
fibList.add(fibNum);
}
}
//Picks out the even numbers from limitFibList
for (int i = 0; i < fibList.size(); i++)
{...
Am I missing something? Why do you need to create list? You just need a sum of even-valued numbers? Right? If I understand you correctly you can get your sum in 10 lines of code... I don't have Java IDE opend, so I'll give you Pythone code. If it is what you need I'll convert it into Java.
def fib(n=4000001): # write Fibonacci series up to n
r = 0
a, b = 0, 1
while b < n:
if not b%2 :
print(b, end=' ')
r += b
a, b = b, a+b
return r
OUTPUT:
2 8 34 144 610 2584 10946 46368 196418 832040 3524578
sum = 4613732
public class Euler002 {
int counter = 0;
public int getCounter () {
return counter;
}
public int getFibTotal () {
final int UPPER_LIMIT = 4000000;
int fib1 = 0;
int fib2 = 1;
int newFib = fib1 + fib2;
int total = 0;
while (newFib < UPPER_LIMIT) {
counter++;
fib1 = fib2;
fib2 = newFib;
newFib = fib1 + fib2;
if ((newFib % 2) == 0) {
total += newFib;
}
}
return total;
}
/**
* #param args
*/
public static void main(String[] args) {
Euler002 euler002 = new Euler002();
int total = euler002.getFibTotal();
System.out.println(" Counter = " + euler002.getCounter() + " And Fib Total is " + total);
}
}
The problem is here:
for (int i = 0; i < fibList.size(); i++)
{
if ((Integer) fibList.get(i) % 2 == 0)
{
evenNumsFibList.add(fibList.get(i)); <-- HERE
}
}
You're adppending a whole new list of all the even numbers to the end of the list you already have.
You need to delete everything in evenNumsFibList before calling this loop again, or modify the loop to only add even numbers that are not already in the list.
That's assuming your indentation is incorrect. If your indentation is actually how you want it, then you're simply missing a closing bracket on your while loop.

Java Enhanced For Loop

How would I write the following for loop using an enhanced for loop>
int [] info = {1,2,3,4,5,6,7,8,9,10};
int i;
for (i = 0; i < info.length; i++) {
if ((i+1) % 10 == 0)
System.out.println(info[i]);
else
System.out.println(info[i] + ", ");
}
I am trying the following, but i guess im doing it incorreclty
for(int i: info){
body here///
Your syntax is correct. The difference is only that you're assigning the actual int value to i instead of the loop index. Thus, if you replace (i+1) % 10 by i % 10 and info[i] by i, it will work correctly.
int[] info = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i : info) {
if (i % 10 == 0)
System.out.println(i);
else
System.out.println(i + ", ");
}
To learn more about the enhanced for loop, check this Sun guide.
The above can by the way be shortened with help of the ternary operator ;)
int[] info = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i : info) {
System.out.println(i + (i % 10 == 0 ? "" : ", "));
}

Categories

Resources