Java Varargs: find index of a number in array - java

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.

Related

Java program calculates average of variable array, input from command line, displays results

Below is what I have so far. The instructions are to create a simple java program that calculates the avg of a variable quantity of ints. Args array for main, no Scanner object, find and display highest and lowest value. Static method that takes user input as argument & returns values. Should display welcome message at launch.
So I think the start of my code is correct! It compiles for me. But I'm not sure how to get user input w/o scanner. I assume I need to use an array in the static method to translate the input into an argument. Which at execution would be java CalculateAverage 1, 2, 5, 9, 20?
And then would I call MATH? So I can display all the values of min max & avg? Am I on the right track..? The questions are specific in the code. Sorry, first time posting here!
public class CalculateAverage {
public static void main(String[] args) {
System.out.print("Hello welcome to the Average Calculator");
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
//do i just keep going and adding letters til j?
//or is there an easier way to do this..?
minArray(array);
maxArray(array);
sumArray(array);
avgArray(array);
}
public static double maxArray(double[] array){
double max = Double.NEGATIVE_INFINITY;
//tbh i saw this on a tutorial, idk if NEGATIVE_INFINITY would
//work for me?
for (int i = 0; i < n; i++)
if (array[i] > max) max = array[i];
System.out.println("The maximum of your array is:" + max);
}
public static double avgArray(double[] array){
double sum = 0.0;
for(int i = 0; i < n; i++)
sum += array[i];
double avg = sum / n;
System.out.println("The average value of your array is: " + avg);
} //then i would make another static for the min but probably before max
}
From the command line, you want to execute
javac CalculateAverage.java
to have Java compile the class and prepare to run it. Then you can execute the code with
java CalculateAverage arg0 arg1 arg2 ...
Now, in your main( string[] args ) method, I see you're creating an array with 11 elements. This is not necessary, and it is not ideal - what if the user gives more than 11 arguments when they're running the program? The better way to do this is:
int[] array = new int[ args.length ]()
This creates a new array of ints, of the same length as the array args - every array has that property length that states how many elements the array has. Now, we haven't actually put anything in array yet, but we know that it has space for the same number of arguments as the program gave. Now, to initialize each element:
for(int i = 0; i < args.length; i++) {
array[i] = Integer.parseInt(args[i])
}
A for loop creates a variable i (this is the int i = 0 part), initialized to 0, and then executes the code inside the curly brackets. After it's done, it increases the value of i by one (this is the i++ part), and runs the code inside the curly brackets again, continuously, until the condition i < args.length is false. Altogether, this iterates through every element of args and initializes the corresponding element of array.
Now, you could use the Math module to do the calculations for you, but you're almost there in doing it yourself. Here's a slight touch-up to maxArray, for example:
public static int maxarray(int[] array) {
int max = array[0]
for (int i = 1; i < array.length; i++) {
if (array[i] > max) max = array[i];
}
}
System.out.println("The maximum of your array is:" + max);
}
I'm using int here because the inputs were ints. In general you should probably make sure that everything is the same type of variable; either make all the numbers ints or make them all doubles, but don't try to go back and forth between them.
You don't actually need negative infinity for anything; you can just start with the first number in your array, call that the maximum, and then for every number afterwards, replace the maximum if it's larger. We use the for loop in the same way here, to iterate over the entire array.
Similarly, you're doing avgArray(double[] array) correctly already - except that I don't know where you got the variable n from (you should be using array.length again).
Overall, I recommend looking back over your notes for this class so far, and carefully make sure you know what everything means and how it applies to this example. Review what you've been taught about how Arrays work; and about the differences between ints and doubles.
This is what I would do. Hopefully the code is simple and self-explanatory but let me know if any questions:
public static void main(String[] args) {
System.out.println("Hello welcome to the Average Calculator");
int numArgs = args.length; //Since args is an array we can get the number of elements with .length
int min = Integer.MAX_VALUE; //The maximum possible value an int can be
int max = Integer.MIN_VALUE; //The minimum possible value an int can be
double total = 0;
for(int i = 0; i < numArgs; i++) {
int nextI = Integer.parseInt(args[i]);
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
System.out.println("The average is: " + total/numArgs);
System.out.println("The min is: " + min);
System.out.println("The max is: " + max);
}
Then, you would run the code like this:
java CalculateAverages 1 2 3 4 5 6 7 8 9
Hello welcome to the Average Calculator
The average is: 5.0
The min is: 1
The max is: 9
Edit:
The instructions said "To find these value, make static methods that
take the user input as arguments & returns the value"
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
System.out.println("The average is: " + getInputAverage(userIntInputs));
System.out.println("The min is: " + getInputMin(userIntInputs));
System.out.println("The max is: " + getInputMax(userIntInputs));
}
private static int getInputMax(int[] userIntInputs) {
int max = Integer.MIN_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] > max) {
max = userIntInputs[i];
}
}
return max;
}
private static int getInputMin(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] < min) {
min = userIntInputs[i];
}
}
return min;
}
private static double getInputAverage(int[] userIntInputs) {
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
total += userIntInputs[i];
}
return total/userIntInputs.length;
}
One Method Alternative
Idk if she means to make a method for each value or one method!
Yeah teachers can be confusing all right. Here's a one method approach...
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
Object[] inputMetrics = getInputMetrics(userIntInputs);
System.out.println("The average is: " + inputMetrics[0]);
System.out.println("The min is: " + inputMetrics[1]);
System.out.println("The max is: " + inputMetrics[2]);
}
private static Object[] getInputMetrics(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
int nextI = userIntInputs[i];
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
Object[] metrics = {total/userIntInputs.length, min, max};
return metrics;
}
Simplicity is IMHO the best way. This does the whole thing:
DoubleSummaryStatistics stats = Arrays.stream(args)
.collect(Collectors.summarizingDouble(Double::parseDouble));
System.out.println("The minimum of your array is: "+ stats.getMin());
System.out.println("The maximum of your array is: "+ stats.getMax());
System.out.println("The sum of your array is: "+ stats.getSum());
System.out.println("The average of your array is: "+ stats.getAverage());
When there's a built-in library to handle something, use it.

How to find the highest and the lowest number stored in an array? [duplicate]

This question already has answers here:
How to find max and min value [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to print the highest and lowest integer number stored in an array. I am able to print the highest but for the lowest I am not getting the correct result.
Consider my two classes below :
class ArrayUtilityNew
{
public static int findMaxMin(int a[])
{
int n=a.length;
int n2=n-1;
int minNo=0;
int count=0;
int maxNo=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]<a[j])count++;
}
//This gives the highest no. if the count is 0
if(count==0)
{
maxNo=a[i];
}
//Lowest no. shall be gained here if the count is greater
// than the no of elements in the array
// if(count>n)
// {
// minNo=a[i];
// }
count=0;
}
return maxNo;
}
}
class ArrayInteractionsNew
{
public static void main(String arr[])
{
int one[]={3,20,1999,2,10,8,999};
int answer=ArrayUtilityNew.findMaxMin(one);
System.out.println("The highest no in the array is "+answer);
}
}
Is the logic behind the second if not correct or is there some other mistake?
How can it be corrected?
You could return an int[] of min and max. Start with an array of two elements, loop over the array1 like
public static int[] findMinMax(int[] a) {
int[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE };
for (int i : a) {
result[0] = Math.min(result[0], i);
result[1] = Math.max(result[1], i);
}
return result;
}
The result will be an array with the first element being the minimum value2. Then to test it,
public static void main(String[] args) {
int[] arr = { 3, 20, 1999, 2, 10, 8, 999 };
int[] minMax = findMinMax(arr);
System.out.printf("%s: min=%d, max=%d%n",
Arrays.toString(arr), minMax[0], minMax[1]);
}
And I get (as I would expect)
[3, 20, 1999, 2, 10, 8, 999]: min=2, max=1999
1Here, with a for-each loop.
2And the second element being the maximum.
I think your solution is way too complex... A better and more efficient solution would be this:
int n=a.length;
int minNo=a[0];
int maxNo=a[0];
for(int i=1;i<n;i++)
{
if(a[i] > maxNo) {
maxNo = a[i];
} else if(a[i] < minNo) {
minNo = a[i];
}
}
// do whatever you want with maxNo and minNo
Also an even more efficient (in the code size way) way would be to use lists or streams because you can do one-liners with it.
EDIT: less ambiguous code and explanations about efficiency
Your answer is n^2. To find min and max it only needs to be order n.
In other words you only need to look linear.
Do a loop that looks through the list once. Keep track of min and max as you go. Initially set min = maxvalue and max=minvalue. When you find a value smaller than min, it becomes the new min.
Here is an example in pseudo code.
min = max_int
max = min_int
for (i=0; i < array.length; i++)
if array[i] < min
min = array[i]
if array[i] > max
max = array[i]
Your approach, if it even works, is needlessly complicated.
Create two variables: minNo and maxNo.
Set minNo = Integer.MAX_VALUE and maxNo = Integer.MIN_VALUE.
Loop through the array. If the element is >= maxNo, assign its value to maxNo. Also (not instead -- i.e., not else if!), if the element is <= minNo, then assign its value to minNo.
After the loop, minNo and maxNo will be correctly assigned.
public static void minMax(int []arr){
int min = arr[0];
int max = arr[0];
for(int i=1; i<arr.length; i++){
min = Math.min(min,arr[i]);
max = Math.max(max,arr[i]);
}
//do whatever you want with the max and min
}
Thanks to the Streaming API in java8, this is a two-liner:
int[] array = new int[] {5,7,2,9,10,24,3,23};
int min = IntStream.of(array).min().getAsInt();
int max = IntStream.of(array).max().getAsInt();
Or as a more efficient 3-liner:
Arrays.parallelSort(array);
int min = array[0];
int max = array[array.length -1];

Smallest and second smallest in an array

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.

How to find highest value from an array, if there are more than one high value?

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.)

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException in Finding Max Element

Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.

Categories

Resources