Getting the sum of numbers from a text file - java

Text File:
2 3
5 5
6 6
3 4
3 4
4 5
5 6
3 3
4 5
For school, one part of a program we had to make was to get "The sum of the scores on the hole that is the highest for all the holes played." Basically, the program had to read from the text file above, and had to display which line had the highest sum. For example, line 1 has a sum of 5, line 2 has a sum of 10, etc. The output should be "12", since line 3 has the highest sum.
What I tried to do was to create two variables: currentSumScore and sumScores. currentSumScore was a test, and sumScores would contain the highest sum.
for (int roundNum = 1; roundNum <= 9; roundNum++)
{
player1Score = in.nextInt();
player2Score = in.nextInt();
currentSumScore = player1Score + player2Score;
if (currentSumScore >= player1Score + player2Score)
{
sumScores = currentSumScore;
}
else
{
sumScores = player1Score + player2Score;
}
}
What I tried doing here was to add the first two numbers of the first line and set that equal to currentSumScore. Then, I put in an if-else. If line 2 had a sum that was greater than line 1, ten sumScores would replace that. I tried this but it is only returning the sum of the last line.

currentSumScore = player1Score + player2Score;
if (currentSumScore >= player1Score + player2Score)
You make currentSumScore to be the sum of player1Score + player2Score, so when it checks the if condition, it will always be true. You need to compare the current sum with the greater value found until then.
currentSumScore = player1Score + player2Score;
if (currentSumScore >= sumScores )
{
//Actual sum is greater than previous
sumScores = currentSumScore;
}
else
{
//Do nothing, this line is not greater than one found before
//This else is not needed
}
And start with a sumScores of a small value so the first line will always be greater (0, -1...)

currentSumScore = player1Score + player2Score;
if (currentSumScore >= player1Score + player2Score)
You are setting currentSumScore = player1Score + player2Score
Then you are saying if it is > OR = to. It is always going to be equal to hence the line before it.
Start with currentSumScore = 0 before reading any of the scores and then check to see if player1Score + player2Score is >, not >=.

You must check against the last value you saved in
sumScores
if (currentSumScore > sumScores) {
sumScores = currentSumScore;
}
And no need to else part. Give this a try, it should work.

Related

segregate list elements with different groups in java

Suppose I have one list which always has the count of even number. Now I want to segregate the list with different group indexes with below conditions,
1) First element (1st element) with one index (EX: 1)
2) Next two elements with same index (Ex: 2nd, 3rd element with index 2,
4th and 5th element with index 3)
3) Last element(6th element) with index 4
I tried with nested for loops to achieve the same, but didn't get the expected output.
Any help is appreciated.
Sample Input:
[2,3,53,52,33,12,44,66]
Sample Output:
2 - 1
3 - 2
53 - 2
52 - 3
33 - 3
12 - 4
44 - 4
66 - 5
I have implemented this using the two additional variables z and count, I am
incrementing z only if the count%2 is 0, and at-last we need to check if the
size-1 is equal to the i variable for the third condition.
Also, for the first condition I am printing the arraylist value at first index and z variable value at i iff the i counter value is 0.
Please see the below code that I have simulated for your input list that I
have added manually ! Please use the link to test :
http://rextester.com/ESYF23501
import javafx.collections.ArrayChangeListener;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(53);
a.add(52);
a.add(33);
a.add(12);
a.add(44);
a.add(66);
int i = 0;
int z = 2;
//Count to group the middle number by checking its value with respect to mod 2
int count = 0;
for(i = 0; i < a.size(); i++)
{
if(i == 0 )
{
z = i+1;
System.out.println(""+a.get(i)+" " + "" +z+"" );
}
if(i > 0 && i != (a.size() -1))
{
//Increament z if the count is even so that we print the group for two times
if(count%2 == 0)
{
z++;
}
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
count ++;
}
if(i == a.size() -1 )
{
z++;
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
}
}
}
}
This should work correctly if I understood your question right:
System.out.println(elements.get(0) + " - 1"); // Prints the first number, which has the value of 1
int value = 2; // Value corresponding to the number
for (int i = 1; i < elements.size(); i++) { // Loops through the list starting at second element (index of 1)
System.out.println(elements.get(i) + " - " + value); // Prints the number and the value
if (i % 2 == 0) value++; // Increases the value every two loops
}
It starts by printing out the first number and 1, which as you described always corresponds to each other. Then it loops through the list of numbers starting at the second number (i = 1), and prints out each number and the corresponding value. The value increases every two loops, which is every time the loop number is divisible by 2 (i % 2).

Error while attempting to solve project euler assignment

I'm working on solving the 14th project euler assignment.
This is the assignment:
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
This is my code:
package collatzSequence;
public class CollatzSeq {
public static void main(String[] args) {
int count = 0;
int largestCount = 0;
for (int i = 13; i < 1000000; i++) {
// System.out.println(i);
int Number = i;
while (Number > 1) {
count = 0;
if (Number % 2 == 0) {
Number = i / 2;
System.out.println("Even: " + Number);
} else {
Number = (Number * 3) + 1;
System.out.println("Uneven: " + Number);
}
count+=1;
if (count > largestCount) {
largestCount = count;
System.out.println("New largest found");
}
}
}
}
}
Now, here's my problem. Everytime I run the program, it prints "Even: 6" over and over again. And its supposed to divide it by half if its even.
Does anyone recognize any problem with my code?
It's becuase of the following if condition in the while loop:
if (Number % 2 == 0) {
Number = i / 2;
System.out.println("Even: " + Number);
}
Here, number is assigne i/2 value, resulting in 6 and then, it never changes, resulting in an infinite loop.
Changing Number = i / 2; to Number = Number / 2; should do.
Your problem is here:
Number = i / 2;
Should be:
Number = Number / 2;
You want to halve the current number, not set Number equal to the starting number divided by 2.

for loop wrong, or equation wrong. what do I need to write after my if statement?

I have just started learning java in netbeans at university. I have written a code to multiply the numbers between 4 and 30 by 3, so that my code will only print out the numbers >= to 4 and will not exceed 30 when multiplied by 3.
I would like my code to print out there are 7 integers greater or equal....etc but my code prints out there are 11 integers I always get confused as to what I need to write after my for or while loops, I am pretty sure my maths is right but why is it calculating to 11 instead of 7?
public static void main(String[] args) {
int start = 4, stop = 30, multiple = 3;
countMultiples(start,stop, multiple);
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++)
if(numbers * multiple <= stop)
numbers++;
System.out.println("there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
System.out.println("which multiplied by " + multiple);
}
You have logic mistake at if condition inside for loop you just need to multiply i * multiplein order to get the expected result:
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++) {
if (i * multiple <= stop) { // <-- the numbers should be i
numbers++;
} else {
break;
}
}
}
Basically what you are doing inside the if is
first you are multiplying with the number which starts from 0 and upon multiplication the overall result is <=30 and your if condition satisfies and it increment your count.
*The difference that you are getting in your count is because you are starting from 0 ,but as you mentioned your number should begin from 4.
So instead of
if(numbers * multiple <= stop)
numbers++;
do this
if(i*multiple <=stop)
numbers++;
Since now you start from i which has its initial value as 4, you shoukd get the right count
You missed the logic here if(numbers * multiple <= stop)
Do it like this
for(int i = start; i <=stop; i++)
if(i * multiple <= stop)
numbers++;
okay first thing first, 4 and 30 are not included right ?
so when setting the i add 1 to it.
then in the condition of the loop remove the equal sign , so it will stop before reaching the number 30.
for(int i = start+1 ; i <stop; i++){//start checking from number 5 , remove the equal sign
if(multiple* i < stop){ //also remove the equal sign here
numbers++;
System.out.println(multiple* i+" :there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
}

Replacing Multiples of numbers in Fibonacci series using Flag method

As the title suggests, I have code for a Fibonacci series and my goal is to replace multiples of numbers (3, 5, 7 and combinations of them) in the series with a word. I was suggested to use a flag in my if loop to check for the printed phrase, and if the phrase is printed, to skip that number. Essentially, what I want the output to look like is:
1 1 2 skip 8 13 skip 34 55
(this is replacing multiple of three only, for now).
Instead, what I am getting is:
1 1 2 3 skip5 8 13 21 skip34 55
Here is my code as of now:
int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
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] + ((i % 10 == 9) ? "\n" : " "));
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Any and all help is appreciated!
Let's walk through the code you have provided and attempt to understand why it's not working.
//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
//Here we print out the fibonacci number we are on, unconditionally.
//This means that every fibonacci number will be printed no matter what number it is
//we don't want that.
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
//After we print the number, we check to see if it is a multiple of three.
//maybe we should be waiting to print until then?
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Now that we have walked through the code, we can propose a new solution.
Let's try updating the loop so that it wait's to print the fibonacci number until AFTER we've checked to see if it meets our conditions.
for (int i = 0; i < febCount; i++) {
if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
System.out.println(" Skip ");
} else { //if it's not a multiple, then print the number
System.out.println(" " + feb[i]);
}
}

Java Netbeans 6.5 Mastermind Calculating White Pegs

For my Mastermind Game I am using 6 numbers instead of 6 colours. Also instead of showing black and white pegs, just 2 sentences are outputted. One reads:
"The number of correct digits in the right position is __ "(black pegs/bothRight)
"The number of correct digits in the wrong position is __ "(white pegs/numberRight)
For the 4 digit guesses that are submitted, I am using an array called guessArr, which accepts 4 values from 4 input boxes.
guess0 = Integer.parseInt(firstInput.getText());
guess1 = Integer.parseInt(secondInput.getText());
guess2 = Integer.parseInt(thirdInput.getText());
guess3 = Integer.parseInt(fourthInput.getText());
//New array to arrange guesses
int[] guessArr = new int[] {guess0,guess1,guess2,guess3};
For the answer generated by the computer,
//Create a 4 digit code made of random numbers between 1 and 6
answerArr[0]=(int)(Math.random()*6+1);
answerArr[1]=(int)(Math.random()*6+1);
answerArr[2]=(int)(Math.random()*6+1);
answerArr[3]=(int)(Math.random()*6+1);
Finding the amount of black pegs is easy:
//Calculate number of correct digits in correct position
for (int i = 0; i < 4; ++i)
{
if (answerArr[i] == guessArr[i])
{
used[i] = true;
bothRight++;
}
}
EDIT
I've Solved It!
// Calculate number of correct numbers in wrong position
//Declare variables for what digits are in the answer
Integer digit1 = 0, digit2 = 0, digit3 = 0, digit4 = 0, digit5 = 0 , digit6 = 0;
//Find what the answer digits are
for (int k = 0; k < answerArr.length; ++k){
if (answerArr [k] == 1)
{
digit1++;
}
if (answerArr [k] == 2)
{
digit2++;
}
if (answerArr [k] == 3)
{
digit3++;
}
if (answerArr [k] == 4)
{
digit4++;
}
if (answerArr [k] == 5)
{
digit5++;
}
if (answerArr [k] == 6)
{
digit6++;
}
}
//Declare variables for what digits are in the answer
Integer gDigit1 = 0, gDigit2 = 0, gDigit3 = 0, gDigit4 = 0, gDigit5 = 0 , gDigit6 = 0;
//Find the guess numbers submitted
for (int p = 0; p < guessArr.length; ++p){
if (guessArr [p] == 1)
{
gDigit1++;
}
else if (guessArr [p] == 2)
{
gDigit2++;
}
else if (guessArr [p] == 3)
{
gDigit3++;
}
else if (guessArr [p] == 4)
{
gDigit4++;
}
else if (guessArr [p] == 5)
{
gDigit5++;
}
else if (guessArr [p] == 6)
{
gDigit6++;
if (gDigit6 == 0)
{
gDigit6++;
}
}
//Find the value of correct numbers submitted in the guess
Integer correctNumbers = Math.min (digit1, gDigit1) + Math.min (digit2, gDigit2) + Math.min (digit3, gDigit3) +
Math.min (digit4, gDigit4) + Math.min (digit5, gDigit5) + Math.min (digit6, gDigit6);
//Calculate value of numberRight
numberRight = (correctNumbers - bothRight);
}
Any help would be greatly appreciated. :D Thanks.
First, I'll say up front, I'm not going to give you any code since this is either a learning exercise, so you can learn the language, or else this is a class problem.
So, lets think about this logically... One way you can you can solve this is by counting the number of a type of colors.
As an example, suppose the player guessed 2 blues, and 2 greens, and the answer has 1 blue, 1 red, and two greens.
The player guessed 3 of the right colors, so you would give them 3 white pegs UNLESS they got some in the right spot. Now, suppose that they got one of those blues in the right spot, that means they have 1 black peg, which replaces a white peg. So, the grand total is 2 white pegs, and 1 black peg.
So, to find the number of "Correct Colors" you should check each color (good chance for a loop?) and compare the number of each color that the player guessed, to the number of each color that the solution has.
Put another way, you don't want to compare the guess to the answer. You want to compare the count for each color on the guess, to the count of each color on the solution.
Then, you get "White pegs" by this pesudo-code:
int whitePegs=correctColors-blackPegs;
Edit 1: Comparing answers one color at a time
If you're going to hold the count for each color, then you're going to want to use two arrays, one for the guess, and one for the solution. Each element in the array will hold the count for the color, like this:
r=red, o=orange, y=yellow, etc.
R O Y G B
Guess: [0][2][1][1][0] (Total is 4, for 4 pegs
Actual: [1][1][2][0][0] (Total is 4) for 4 pegs
Matches:[0][1][1][0][0] (Total is 2) This is "correctColors" from above

Categories