Directions:
Given an int[] x
and a percentage p (0 - 100), find the smallest valued element y
of x
so that at least percentage p
elements of x
are less than or equal to y
.
Example 1:
x = {-3, -5, 2, 1}, p = 50
Method should return -3
Reason: 50% of the elements in x are less than or equal to -3: -5 and -3
Example 2:
x = {7, 9, 2, -10, -6}, p = 50
Method should return 2
Reason: 60 percent of the elements in x are less than or equal to 2: 2, -10 and -6
-6 would be wrong because only 40% of the elements are less than or equal
(100% of the elements are less than or equal to 9, but that isn't the smallest value)
Example 3:
x = {1,2,3,4,5,6,7,8,9,1,2,3,4,5,7,9,5,43,124,94}, p = 0
Method should return 1
Reason: Only 0% is needed, so in theory any number will do, but 1 is the smallest value
Here is what I've written for the method so far:
public static int fractile(int[] x, int p)
{
int smallestInt = x[0];
for (int i = 0; i < x.length; i++) {
int testNum = x[i];
int percentage;
int count = 0;
for (int j = 0; j < x.length; j++) {
if (x[j] <= testNum)
count++;
}
percentage = (count / x.length) * 100;
if (testNum <= smallestInt && percentage >= p)
smallestInt = testNum;
}
return smallestInt;
}
But my output for my sample numbers comes out wrong:
INPUT:
[6, 5, 4, 8, 3, 2]
40%
Method returns: 6
INPUT:
[7, 5, 6, 4, 3, 8, 7, 6, 9, 10]
20%
Method returns: 7
INPUT:
[3, 4, 2, 6, 7, 5, 4, 4, 3, 2]
60%
Method returns: 3
It's almost as if it's grabbing the first index and doesn't look at the numbers behind it but I can't figure out why.
What am I doing wrong?