I've looked at the answer posted here (finding smallest and second smallest number) but I cannot get my code to work.
Here is what I have.
public static void shortestTimes(int[] times){
int counter = 0;
int secondLowest = times[counter];
int min = times[counter];
for (counter = 0; counter < times.length; counter ++) {
if (times[counter] < min) {
secondLowest = min;
min = times[counter];
} else if (times[counter] < secondLowest) {
secondLowest = times[counter];
}
}
System.out.println("The fastest time was: " + min + ". And the second fastest was: " + secondLowest);
}
When I put in the input:
int[] values = {1, 3, 3, 2, 5};
longestTimes(values);
I get the output:
The fastest time was: 1. And the second fastest was: 1
Why is my second lowest number not getting changed?
Your second lowest value is not getting changed because from the beginning you are setting secondLowest to be equal to the value at values[0], which is your lowest value in the array. If I were you, I would initialize both min and secondLowest to Integer.MAX_VALUE. Then the algorithm would behave as expected
Firstly when you declare min and secondLowest I would check if times.length >= 2.
I would then assign them with:
min = times[0];
secondLowest = times[1];
The problem is with your declaration of secondLowest and the fact that they both start at the lowest value. You don't have any sort of check to see if min and secondLowest are referring to the same number within the array.
If the array is guaranteed to contain unique values this isn't an issue, but if not you should change around your search. Sorting the array would help too.
Related
I am trying to find an index of a number in array. I am using varargs method.
My task was to find minimum of numbers and then find his position.
public static void main(String[] args) {
System.out.println(minimum(2.4, 4.5, -11.3, 3.9, -7.2, -12.1, 14.8));
}
public static double minimum(double... n) {
int k = 0;
double min = n[k];
for (double i : n) {
k++;
if (i < min) {
min = i;
}
if (min == n[k - 1]) {
System.out.println("minimum number index is " + (k - 1));
}
}
return min;
Outcome is this
index of minimum: 0
index of minimum: 2
index of minimum: 5
-12.1
When i put System.out.print outside of for loop printing last value for k. Thank you in advance.
Hope this helps. Just got to keep the min index in a variable just like storing min value.
public static double minimum(double... n) {
int k = 0;
double min = n[k];
minIndex = k;
for (double i : n) {
k++;
if (i < min) {
min = i;
minIndex = k-1;
}
}
System.out.println("minimum number index is " + (minIndex));
return min;
}
You are almost there !
As you correctly recognized, your variable k holds the index + 1 of the double you are looking at in your for loop.
If you want to keep the index of the smallest value in the array, you need to do the same thing you did with variable min. You need an additional variable which you initialize outside the loop. When you find a new "smaller value" in the array, you store the k-1 in this variable.
When you exit the for loop, that variable will hold the index of the smallest value in the array.
I am doing some exercises on codingbat because I have been struggling with arrays. The question was:
"Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more."
I was able to code the solution correctly except for 1 part.
The correct code is:
public int centeredAverage(int[] nums) {
int max = nums[0];
int min = nums[0];
int add = nums[0];
for(int i = 1; i < nums.length; i++){
add += nums[i];
if(nums[i] > max){
max = nums[i];
}
else if(nums[i] < min){
min = nums[i];
}
}
return (add - max - min) / (nums.length - 2);
}
My question is why are we starting at int i = 1 rather than 0? If you start at 1 aren't you skipping over a cell?
The initialization:
int max = nums[0];
int min = nums[0];
int add = nums[0];
handles the case when i = 0 for you.
As you are setting max, min and add from zero index of array.By doing this u are finding min and max from a single loop iteration(i.e.. by compairing this values from the other elements of array). If u havn't done this then u have to use some other logic to find min and max of array like O(n)^2 soln.
Here are fragments of the code I have so far. My problem is that the min values come up as Integer.MAX_VALUE, instead of the value I want. iSpeedMph and pressure are both one-dimensional integer arrays.
//calculating mins
Integer min = Integer.MAX_VALUE;
int minSpeed = Integer.MAX_VALUE;
int minPressure = Integer.MAX_VALUE;
for(i = 0; i < iSpeedMph.length; i++)
{
if (min > iSpeedMph[i])
{
min = iSpeedMph[i];
minSpeed = iSpeedMph[i];
}
}
min = Integer.MAX_VALUE;
for(i = 0; i < pressure.length; i++)
{
if (min > pressure[i])
{
min = pressure[i];
minPressure = pressure[i];
}
}
...
System.out.printf("%7s%2s%-9s%4s%8s%5s%13.3s%5s%16.2s\n", "Minimum", " ", " ", " ", " ", " ", minPressure, " ", minSpeed);
When I print out the last line, the terminal shows 214 for pressure and 21 for speed, which, without the formatting, means that they are both Integer.MAX_VALUE.
You are checking if the current item is greater than the current min, which is Integer.MAX_VALUE, but you want to check if the current item is less than the current min instead, e.g.
if (iSpeedMph[i] < min)
and likewise for the other min determinations.
The test
if (iSpeedMph[i] > min)
always returns false. You have to reverse the comparison.
if (iSpeedMph[i] < min)
or as alternative
if (min > iSpeedMph[i])
The below condition will never become true for any integer, since min is Integer.MAXVALUE.
if (iSpeedMph[i] > min)
just initialize it 0, to check if you are searching min of all in array or, assign min with first array value and loop the array from 2nd element.
if (iSpeedMph[i] > min) how could this give you the new min value?
Also, please use min methods already written for you, e.g. https://stackoverflow.com/a/1658144/499922
As others have pointed out you have the comparison in the if statements wrong. But finding min and max in arrays is very simple with Java 8 streams :
int minSpeed = Arrays.stream(iSpeedMph).min().get();
int minPressure = Arrays.stream(pressure).min().get();
I have a sorted array. Let's say it is int [] numArr=new int[]{6, 9, 10, 27};
The smallest distance is between the 9 and the 10, and it is 1. The program should print this 1.
I am not expecting code, but I hope someone can give me an idea of how to proceed.
Declare a variable to hold the current minimum distance. It can be initialized to a really large number Integer.MAX_VALUE so that the first distance calculated becomes the initial minimum distance.
Use a for loop to loop over the values. You'll be accessing the element at the current index and the next index, so stop your for loop early to prevent an ArrayIndexOutOfBoundsException.
In the for loop, calculate the difference. If the difference is less than the current minimum, then update the current minimum to the current difference.
public static final int findSmallestDistance(final int[] pArray) {
int lMinimumDistance = Integer.MAX_VALUE;
for(int i = 1; i < pArray.length; i++) {
int lDifference = pArray[i] - pArray[i - 1];
if(lDifference < lMinimumDistance) {
lMinimumDistance = lDifference;
}
}
return lMinimumDistance;
}
Step 1: create a variable to save the actual smallest distance
Step 2: iterate through your array
Step 3: compare your actual number with the previous on your array (if this is the first element jump this step) and if it's smaller than your smallest save the result
Step 4: if the array has more elements, get the next one, else print your result
Here's some pseudocode:
Be smallest = a number surely greater than the one you're looking for
For each element i in array except the first
Be n = array[i] - array[i-1]
If n < smallest then
smallest = n
End If
End For
int numArr[] = {6, 9, 10, 27};
for(int i=0;i<numArr.length-1;i++){
if(numArr[i+1]-numArr[i]>0){
System.out.println("distance between " +numArr[i]+ " and "+numArr[i+1]+ " is: "+ (numArr[i+1]-numArr[i]));
}
}
int smallest = 100000
for (int i = 0; i < array.length; i++)
if(array[i+1]-array[i]<smallest)
{
smallest = array[i+1]-array[i];
}
System.out.println(smallest);
I have an array which I would like to find the highest value for, but this value might be repeated.
For example, consider this array of integers:
{10, 2, 6, 25, 40, 58, 60, 60}.
//Here the value 60 is repeated
Here, I would like the output to show that there are two highest values in this array. Like in upper example it have to be show that 60 is highest value among all values in array and that value is 2 time available in array. And i do not want like to count how many numbers but like addition of that two highest numbers. I have search programs but i could not find any relevant solution for this.
class Cal
{
void CalculateThis()
{
int[] myArray = new int[] {20,10,5,40,20,41,41,2,6,7,3,4,5,6,23,34,7,8,9,2};
int max = Integer.MIN_VALUE;
int sum=0;
for(int i = 0; i < myArray.length; i++)
{
if(myArray[i] > max)
{
max = myArray[i]*3;
sum = sum + max;
}
}
System.out.println(sum);
}
}
class program1
{
public static void main(String args[])
{
Cal obj = new Cal();
obj.CalculateThis();
}
}
int max = ar[0];
int maxSum = 0;
for (int i=1; i< ar.length; i++)
{
if(ar[i] > max)
max = ar[i];
else
if(ar[i] == max)
maxSum+=max;
}
int[] myArray = { 10, 2, 6, 25, 40, 58, 60, 60 };
int max = Integer.MIN_VALUE;
int maxCount = 0;
for (int x : myArray) {
if (x > max) {
max = x;
maxCount = 1;
} else if (x == max) {
maxCount++;
}
}
int maxSum = max * maxCount;
System.out.println("Max value : " + max);
System.out.println("Max Count : " + maxCount);
System.out.println("Max Sum : " + maxSum);
output :
Max value : 60
Max Count : 2
Max Sum : 120
There are various approaches you could take here:
Sort the array using Arrays.sort, then work from the end until you saw a different value... letting you work out the value and the count, which you could then multiply together. This is relatively inefficient, as you don't really need to sort.
Write two methods, one of which returned the maximum value and one of which returned the count of a specific value. Find the maximum first, then the count of that, then multiply together. This requires two passes, but is clean in terms of building the final result from separate and reusable operations.
Write a method to keep track of the max and the sum at the same time, resetting both if you see a higher value. This will probably be the most efficient, but wouldn't be reusable for other requirements. (You could equivalently keep track of a count as you went, and multiply the max by count at the end instead.)