All of this works to some degree. Here's the issue:
1: User specifies array size. Let's assume size = 5.
2: User inputs 1 2 3 4 5
3: MAX number and MIN number works. All good.
ISSUE:
2: User inputs 5 4 3 2 1
3: MAX number fails. It's defaulted to Integer.MAX_VALUE
This is defined above:
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
The Code is here:
for (int i = 0; i < numbers.length; i++) { //READ INPUT, find smallest / largest
numbers[i] = myScanner.nextInt();
sum += numbers[i]; //ADD Array element values to sum.
if (numbers[i] < min) { //Loop through array to find smallest value
min = numbers[i];
} else if (numbers[i] > max) { //Loop through array to find largest value
max = numbers[i];
}
}
Note: This is a code snippet. "sum" belongs to the rest of the code.
Remove the "else", the two conditions can be true.
for (int i = 0; i < numbers.length; i++) {largest
numbers[i] = myScanner.nextInt();
sum += numbers[i];
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] > max) {
max = numbers[i];
}
}
If you dry-run the code
User inputs 5 4 3 2 1
5<min(Integer.MIN_VALUE) so min = 5
4<min(5) so min = 4
3<min(4) so min = 3
2<min(3) so min = 2
1<min(2) so min = 1
Since you are having an else-if condition.
It never goes to the else condition and max is always Integer.MIN_VALUE
So remove the else-if to if condition.
just remove else in your code, because two condition can be true at the same time
Related
This is a problem from SPOJ. I am getting TLE. Need help to improve its time complexity. There is one test-case that i know will fail. But I will take care of it after the time complexity is reduced.
Ada the Ladybug was on a trip with her friends. They each bought a souvenir there. As all of them are mathematicians, everybody bought a number. They want to modify the numbers to have some connection between each other. They have decided to modify the numbers sou they would have their GCD greater than 1 ( gcd(a1,a2,a3,...,aN) > 1). Anyway it is not easy to change a number - the only thing they can do is to go to a proffesor in mathematics, which could forge a number A into number A+1 or A-1. As this operation is not cheap, they want to minimize number of such operations. A number might be forged any number of times.
NOTE: gcd(a,0)==a (so gcd of two 0 is also 0)
Input
The first line contains an integer 1 ≤ N ≤ 3*10^5, the number of friend who were on trip (and also the number of numbers).
The second line contains N integers 0 ≤ a_i ≤ 10^6
Output
Print a single line with minimum number of operations to make a connection between all numbers.
Example Input
5
3 9 7 6 31
Example Output
2
Example Input 2
9
3 4 5 7 8 9 11 12 13
Example Output 2
6
Example Input 3
5
7 7 11 17 1
Example Output 3
5
APPROACH
First i find the primes upto (largest/2 + 1) element in the given array of numbers(using function findPrimes()). And then for every element in the array, find how many operations are going to be needed for each of the primes to be its divisor. The smallest summation for each prime, I am printing as solution.
CODE
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int largest = Integer.MIN_VALUE;
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] strArr = br.readLine().split(" ");
for(int i = 0 ; i < n ; i++)
{
arr[i] = Integer.parseInt(strArr[i]);
if(arr[i] > largest)
{
largest = arr[i];
}
}
func(n,arr,largest);
}
public static void func(int n,int[] arr,int largest)
{
int[] primes = findPrimes(largest / 2 + 1);
//int[] primes = findPrimes((int)Math.sqrt(largest));
int lenOfPrimes = primes.length;
int[] mat = new int[lenOfPrimes];
for(int j = 0 ; j < lenOfPrimes ; j++)
{
if(arr[0] < primes[j])
{
mat[j] = primes[j] - arr[0];
}
else if(arr[0] % primes[j] == 0)
{
mat[j] = 0;
}
else
{
int rem = arr[0] % primes[j];
mat[j] = Math.min(rem,primes[j] - rem);
}
}
for(int i = 1 ; i < n ; i++)
{
for(int j = 0 ; j < lenOfPrimes ; j++)
{
if(arr[i] < primes[j])
{
mat[j] = mat[j] + primes[j] - arr[i];
}
else if(arr[i] % primes[j] == 0)
{
mat[j] = mat[j] + 0;
}
else
{
int rem = arr[i] % primes[j];
mat[j] += Math.min(rem,primes[j] - rem);
}
}
}
int smallest = Integer.MAX_VALUE;
for(int i = 0 ; i < lenOfPrimes ;i++)
{
if(mat[i] < smallest)
smallest = mat[i];
}
System.out.println(smallest);
}
public static int[] findPrimes(int upto)
{
boolean[] primes = new boolean[upto + 1];
for(int i = 0 ; i < upto + 1 ; i++)
primes[i] = true;
int count = 0;
primes[0] = primes[1] = false;
int limit = (int)Math.sqrt(upto + 1);
for(int i = 2 ; i < upto + 1; i++)
{
if(primes[i] == true)
{
count++;
if(i <= limit)
{
for(int j = i * i ; j < upto + 1 ; j += 2 * i)
{
primes[j] = false;
}
}
}
}
int[] primeContainer = new int[count];
int index = 0;
for(int i = 2 ; i < upto + 1 ; i++)
{
if(primes[i] == true)
{
primeContainer[index++] = i;
if(index == count)
break;
}
}
return primeContainer;
}
}
The solution that you are trying will give you correct answer. But since there are many prime numbers till 1000000, (~ 78000) hence 78000*300000 will definately give you TLE.
Try to think in terms of sieve. The sieve of eratosthenes works in O(nlogn) time.
Now you would have already figured out that you would change numbers such that it is divisible by some prime number. (As in your algorithm you are considering only prime numbers). So now lets take a prime number say 7. Now you need to find number of transformation of numbers from 0 to 3, because you need to change these numbers to 0. Similarly you need to find number of numbers from 4 to 10 as you will change them to 7 to get them divisible by 7 considering minimum operations. Similarly you would do the same to numbers from 11 to 17, changing them to 14, and so on for rest of the numbers till 1000000. You need to do the same for all prime numbers. This can be achieved using sieve.
The number of operations in this case will be n/2 + n/3 + n/5 + n/7 + n/11 + .... ~ nlogn.
You can read more about sieve from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
May be its too late but let me answer this.
I was able to sole this problem using below approach.
My Java Solution take 3.8 S on SPOJ for all 15 test cases combine.
1.Find prime divisors of n in O(log n)
Source https://www.geeksforgeeks.org/prime-factorization-using-sieve-olog-n-multiple-queries/
2. While computing factorization store prime divisors in array let say UniquePrimeWhicheDividsAtleastOneNumber[]
here is a catch always keep 2 in this UniquePrimeWhicheDividsAtleastOneNumber if its not available.
UniquePrimeWhicheDividsAtleastOneNumber[0]=2
3. now you can loop through these primes and find the sum of smallest reminders by these primes.
long minTemp = 0, minAns = Long.MAX_VALUE;
for (int i = 0; i < UniquePrimeWhicheDividsAtleastOneNumber.length; i++) {
for (int j = 0; j < n; j++) {
int rem = InputNumbers[j] % UniquePrimeWhicheDividsAtleastOneNumber[i];
minTemp += Math.min(rem, UniquePrimeWhicheDividsAtleastOneNumber[i] - rem);
if (minTemp > minAns)
break;// no need to compute sum of reminders if it exceeded the current minimum.
}
minAns = Math.min(minAns, minTemp);
minTemp = 0;
}
minAns --> is your answer.
I just attempted a stack based problem on HackerRank
https://www.hackerrank.com/challenges/game-of-two-stacks
Alexa has two stacks of non-negative integers, stack A and stack B where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game:
In each move, Nick can remove one integer from the top of either stack A or B stack.
Nick keeps a running sum of the integers he removes from the two stacks.
Nick is disqualified from the game if, at any point, his running sum becomes greater than some integer X given at the beginning of the game.
Nick's final score is the total number of integers he has removed from the two stacks.
find the maximum possible score Nick can achieve (i.e., the maximum number of integers he can remove without being disqualified) during each game and print it on a new line.
For each of the games, print an integer on a new line denoting the maximum possible score Nick can achieve without being disqualified.
Sample Input 0
1 -> Number of games
10 -> sum should not exceed 10
4 2 4 6 1 -> Stack A
2 1 8 5 -> Stack B
Sample Output
4
Below is my code I tried the greedy approach by taking the minimum element from the top of the stack & adding it to the sum. It works fine for some of the test cases but fails for rest like for the below input
1
67
19 9 8 13 1 7 18 0 19 19 10 5 15 19 0 0 16 12 5 10 - Stack A
11 17 1 18 14 12 9 18 14 3 4 13 4 12 6 5 12 16 5 11 16 8 16 3 7 8 3 3 0 1 13 4 10 7 14 - Stack B
My code is giving 5 but the correct solution is 6 the elements popped out in series are 19,9,8,11,17,1
First three elements from stack A & then from Stack B.
**
I don't understand the algorithm It appears like DP to me can anyone
help me with the approach/algorithm?
**
public class Default {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfGames = Integer.parseInt(br.readLine());
for (int i = 0; i < numOfGames; i++) {
String[] tmp = br.readLine().split(" ");
int numOfElementsStackOne = Integer.parseInt(tmp[0]);
int numOfElementsStackTwo = Integer.parseInt(tmp[1]);
int limit = Integer.parseInt(tmp[2]);
int sum = 0;
int popCount = 0;
Stack<Integer> stackOne = new Stack<Integer>();
Stack<Integer> stackTwo = new Stack<Integer>();
String[] stOne = br.readLine().split(" ");
String[] stTwo = br.readLine().split(" ");
for (int k = numOfElementsStackOne - 1; k >= 0; k--) {
stackOne.push(Integer.parseInt(stOne[k]));
}
for (int j = numOfElementsStackTwo - 1; j >= 0; j--) {
stackTwo.push(Integer.parseInt(stTwo[j]));
}
while (sum <= limit) {
int pk1 = 0;
int pk2 = 0;
if (stackOne.isEmpty()) {
sum = sum + stackTwo.pop();
popCount++;
} else if (stackTwo.isEmpty()) {
sum = sum + stackOne.pop();
popCount++;
}
else if (!stackOne.isEmpty() && !stackTwo.isEmpty()) {
pk1 = stackOne.peek();
pk2 = stackTwo.peek();
if (pk1 <= pk2) {
sum = sum + stackOne.pop();
popCount++;
} else {
sum = sum + stackTwo.pop();
popCount++;
}
} else if(stackOne.isEmpty() && stackTwo.isEmpty()){
break;
}
}
int score = (popCount>0)?(popCount-1):0;
System.out.println(score);
}
}
}
Ok I will try to explain an algorithm which basically can solve this issue with O(n), you need to try coding it yourself.
I will explain it on the simple example and you can reflect it
1 -> Number of games
10 -> sum should not exceed 10
4 2 4 6 1 -> Stack A
2 1 8 5 -> Stack B
First you will need to creat 2 arrays, the array will contain the summation of all the number up to its index of the stack, for example for stack A you will have this array
4 6 10 16 17 //index 0 ->4
Same will be done for stack B
2 3 11 16
then for each array start iterating from the end of the array until you reach a number less than or equal to the "sum you should not exceed"
now your current sum is the sum of the point you reached in both arrays, should be 10 +3 = 13 so in order to reach 10 will absolutely need to remove more entries
to remove the additional entries we will be moving the indexes on the array again, to decide which array to move it's index take the entry you are pointing at (10 for array 1 and 3 for array 2) and device it by index+1 (10/3 ~ 3) , (3/2 ~1) then move the index for the highest value and recalculate the sum
Suppose we have:
a = 1 1 1 211 2
b = 1 85
and maxSum = 217
Now, on calculating prefix sums,
a' = 1 2 3 214 216
and b' = 1 86
current sum = 86+216 > 217
so to decide which index to remove, we compare `
216/5~43.2` and `86/2=43`,
so we move pointer in a'. BUT, that doesn't solve it - `
214+86 is still > 217!!`
Had we removed 86, it would've been better! So we should always go ahead by removing the one which has larger difference with previous element!
In case both values are equal its logical to move the index on the value which has larger difference with its previous ( remember we are moving the index in reverse order).
the result will be the sum of the indexes +2.
This solution works great.... i hope it helps ...
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int g = sc.nextInt();
for (int tc = 0; tc < g; tc++) {
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int[] a = readArray(sc, n);
int[] b = readArray(sc, m);
System.out.println(solve(a, b, x));
}
sc.close();
}
static int[] readArray(Scanner sc, int size) {
int[] result = new int[size];
for (int i = 0; i < result.length; i++) {
result[i] = sc.nextInt();
}
return result;
}
static int solve(int[] a, int[] b, int x) {
int lengthB = 0;
int sum = 0;
while (lengthB < b.length && sum + b[lengthB] <= x) {
sum += b[lengthB];
lengthB++;
}
int maxScore = lengthB;
for (int lengthA = 1; lengthA <= a.length; lengthA++) {
sum += a[lengthA - 1];
while (sum > x && lengthB > 0) {
lengthB--;
sum -= b[lengthB];
}
if (sum > x) {
break;
}
maxScore = Math.max(maxScore, lengthA + lengthB);
}
return maxScore;
}
}
solution in python3
# stack implementation
class Stack:
lis = []
def __init__(self, l):
self.lis = l[::-1]
def push(self, data):
self.lis.append(data)
def peek(self):
return self.lis[-1]
def pop(self):
self.lis.pop()
def is_empty(self):
return len(self.lis) == 0
# number of test cases
tests = int(input())
for i in range(tests):
na, nb, x = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
temp = []
stk_a = Stack(a)
stk_b = Stack(b)
score = 0
count = 0
# first taking elements from stack A , till score becomes just less than desired total
for j in range(len(a)):
if score + stk_a.peek() <= x:
score += stk_a.peek()
count += 1
temp.append(stk_a.peek())
# storing the popped elements in temporary stack such that we can again remove them from score
# when we find better element in stack B
stk_a.pop()
# this is maximum number of moves using only stack A
max_now = count
# now iterating through stack B for element lets say k which on adding to total score should be less than desired
# or else we will remove each element of stack A from score till it becomes just less than desired total.
for k in range(len(b)):
score += stk_b.peek()
stk_b.pop()
count += 1
while score > x and count > 0 and len(temp) > 0:
count = count - 1
score = score - temp[-1]
temp.pop()
# if the score after adding element from stack B is greater than max_now then we have new set of moves which will also lead
# to just less than desired so we should pick maximum of both
if score <= x and count > max_now:
max_now = count
print(max_now)
I see that there exist a solution and you marked it as correct, but I have a simple solution
add all elements from stack one that satisfy condition <= x
every element you add push it on stack called elements_from_a
set counter to size of stack
try add elements from stack b if sum > x so remove last element you added you can get it from stack elements_from_a
increment bstack counter with each add , decrements from astack with each remove
compare sum of steps with count and adjust count return count
here is code sample for the solution :
def twoStacks(x, a, b):
sumx = 0
asteps = 0
bsteps = 0
elements = []
maxIndex = 0
while len(a) > 0 and sumx + a[0] <= x :
nextvalue = a.pop(0)
sumx+=nextvalue
asteps+=1
elements.append(nextvalue)
maxIndex = asteps
while len(b) > 0 and len(elements) > 0:
sumx += b.pop(0)
bsteps+=1
while sumx > x and len(elements) > 0 :
lastValue = elements.pop()
asteps-=1
sumx -= lastValue
if sumx <= x and bsteps + asteps > maxIndex :
maxIndex = bsteps + asteps
return maxIndex
I hope this is more simple solution.
void traversal(int &max, int x, std::vector<int> &a, int pos_a,
std::vector<int> &b, int pos_b) {
if (pos_a < a.size() and a[pos_a] <= x) {
max = std::max(pos_a + pos_b + 1, max);
traversal(max, x - a[pos_a], a, pos_a + 1, b, pos_b);
}
if (pos_b < b.size() and b[pos_b] <= x) {
max = std::max(pos_a + pos_b + 1, max);
traversal(max, x - b[pos_b], a, pos_a, b, pos_b + 1);
}
}
int twoStacks(int x, std::vector<int> &a, std::vector<int> &b) {
int max = 0;
traversal(max, x, a, 0, b, 0);
return max;
}
A recursion solution, easy to understand. This solution takes the 2 stacks as a directed graph and traversal it.
The Accepted Answer is Wrong. It fails for the below test case as depicted in the image.
For the test case given, if maximum sum should not exceed 10. Then correct answer is 5. But if we follow the approach by Amer Qarabsa, the answer would be 3. We can follow Geeky coder approach.
I am using arrays for a programming project due tonight. I am able to add up all the numbers of the array, but from there I am unable to remove the maximum and minimum values from it. My attempt and the actual project description is below...
In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a computer program that inputs a degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.
package baker;
import java.util.Scanner;
public class DiveScoreDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double total = 0;
double totalFinal = 0;
double divingScores[] = new double[7];
double input;
double difficultyInput = 0;
double minimum = divingScores[0];
double maximum = divingScores[0];
for (int i = 1; i < divingScores.length + 1; i++)
{
System.out.println("Judge " + i + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
}
}
while (difficultyInput < 1.2 || difficultyInput > 3.8)
{
System.out.println("Difficulty Rating: ");
difficultyInput = keyboard.nextDouble();
}
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
System.out.printf("\nThe overall score for the dive: %.1f\n", total);
}
}
The portion in particular that I am struggling with is here:
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
The code runs and produces a correct output, but it does not seem to subtract the max and min values and the problem requests... Thanks for the help!
You have forgotten to add each judge's score to the array divingScores. You can fix this by changing the first for loop to the following:
for (int i = 0; i < divingScores.length; i++)
{
System.out.println("Judge " + (i + 1) + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
divingScores[i] = input;
}
}
You should also initialize minimum as:
minimum = 0
If you do not, every score above 0 will not be considered for the minimum.
You never set the array values in the else branch within your for loop, it should look like this:
if(input < 0 || input > 10) {
System.out.println("Invalid Score");
return;
} else {
divingScores[i] = input;
total += input;
}
Before the second loop, you can use Java 8 functional programming to get the minimum and maximum like this, which is shorter:
double minimum = Arrays.stream(divingScores).min().getAsDouble();
double maximum = Arrays.stream(divingScores).max().getAsDouble();
Alternatively, you should initialize the minimum and maximum values properly, one way to do this in general for at least one element in the array is:
double minimum = Double.MAX_VALUE; // Use your maximum in your case
double maximum = Double.MIN_VALUE; // Use your minimum in your case
You can sort the array and then add the array elements except first and last element of sorted array which will automatically remove the minimum and maximum
Arrays.sort(divingScores);
double ans=0;
for(int i=1;i<divingScores.length-1;i++){
System.out.println(divingScores[i]);
ans+=divingScores[i];
}
when I execute this program, it prints the max value just fine, however the min value always prints to zero. I continue to scratching my head... Can anyone see what is wrong here? Thanks for looking.
import java.util.Scanner;
public class MinMax
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int [] numbers = new int[5];
int max = numbers[0];
int min = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Enter your next number:");
numbers[i] = kb.nextInt();
if (numbers[i] > max)
{
max = numbers[i];
}
if (min > numbers[i])
{
min = numbers[i];
}
}
System.out.println("The maximum value in your array is " + max);
System.out.println("The minimum value in your array is " + min);
}
}
The issue is that when the array is declared, the ints in the array are set to 0. Setting the min to numbers[0] would set min to 0. If that's not your min, your code will fail.
In this case, you don't need the array - you could just store whatever the user inputted. That aside, just check whether i==0 and when it does, set min and max to numbers[0]. (If you didn't do the same for max, an array of all negatives would fail.)
It's simple. The min variable is never updated because every time that min > numbers[i] is evaluated returns false. Let's to see an example:
min = 0.0 > numbers[i] = 4.5 -> false
min = 0.0 > numbers[i] = 3.8 -> false
min = 0.0 > numbers[i] = -8.9 -> true, min = -8.9
min = -8.9 > numbers[i] = 7.5 -> false
min = -8.9 < numbers[i] = 5.6 -> false
The value of min is: -8.9
With Java 8 you can get the max and min values easy with lambdas:
max = Arrays.stream(numbers).max().getAsDouble();
min = Arrays.stream(numbers).min().getAsDouble();
As other answers here are saying, the problem is that numbers[0] starts out initialized to 0, so regardless of the numbers the user enters, your code still finds 0 to be the minimum value.
What you need is an extra state to represent "I don't have any minimum value yet". You could use an extra boolean variable to represent this tate, or if you can use the Integer wrapper type, you can use null.
For example:
Integer minimum = null;
Integer maximum = null;
for (int i = 0; i < 5; i++) {
int number = kb.nextInt();
if (minimum == null || number < minimum) {
minimum = number;
}
if (maximum == null || number > maximum) {
maximum = number;
}
}
System.out.println("minimum: " + minimum);
System.out.println("maximum: " + maximum);
Here is my assignment:
Write a program to read a list of nonnegative integers and to display the largest integer, the smallest integer, and the average of all the integers. The user
indicates the end of the input by entering a negative sentinel value that is not
used in finding the largest, smallest, and average values. The average should
be a value of type double so it will be computed with a fractional part.
I've gotten different parts to work with different methods: Method A makes the maximum and minimum correct and the sum wrong and Method B makes the sum and maximum correct and the minimum wrong. The following code demonstrates Method B. Some variables are commented out:
public class testthis2
{
public static void main(String[] args) {
System.out.println("Enter Numbers of Nonnegative Integers.");
System.out.println("When complete, enter -1 to end input values.");
Scanner keyboard = new Scanner(System.in);
//int max = keyboard.nextInt();
int max = 0;
int min = max; //The max and min so far are the first score.
//int next = keyboard.nextInt();
int count = 0;
int sum = 0;
boolean areMore = true;
boolean run_it = false; //run it if its true
//if (max <= -1) {
// System.out.println("Thanks for playing!");
// run_it = false;
//}
// else
// run_it = true;
while(areMore) //always true
{
int next = keyboard.nextInt();
//int max = 0;
// min = max;
if (next < 0) { //if -1 is entered end loop.
areMore = false;
run_it = false;
break;
}
else //run this badboy
if(next >= max)
max = next;
else if(next <= min)
min = next;
run_it = true;
sum += next;
count++;
}
if (run_it = true)
System.out.println("The highest score is " + max);
System.out.println("The lowest score is " + min);
System.out.println("count " + count);
System.out.println("sum " + sum);
System.out.println("average " + (double)(sum/count));
System.out.println("Thanks for playing!");
}
}
When I run this test, the maximum, sum, count, and average are all correct. However, the minimum is wrong, because 0 was clearly not entered. Here's an example test-run:
When complete, enter -1 to end input values.
37
25
30
20
11
14
-1
The highest score is 37
The lowest score is 0
count 6
sum 137
average 22.0
Thanks for playing!
Any help would be greatly appreciated. Thanks!
The smallest iteger is always 0 because there is no nonnegative integer that is less then 0 :)
if(next <= min) // for nonnegative integer this expression will return true only for 0
min = next;
So try to initialize the "min" variable as Integer.MAX_VALUE. I believe it will help you.
There are 2 problems with the code:
You initialize min to 0 so it never gets updated because it will always be <= any valid number you enter. Try initializing it to Integer.MAX_VALUE. conversely also initialize max to Integer.MIN_VALUE
You are not correctly computing the average value: (double)(sum/count) will first do integer division which truncates the value THEN gets cast to double do this instead ((double)(sum )/count) or optionally make the type of sum a double.
Looks like you initialize min and max both to 0.
Then the only code that will ever change min or max is based on user input. If the input value (next) is >= max, max will change to that value. This should happen on the first input.
The problem is you try setting min the same way. if (next <= min), but min was initialized to 0, so next can only be <= min if next is less than 0.
You need to initialize max and min on the user's first input. They should both start equal to the user's first input before you compare future inputs to their value.