Java - Finding minimum number - java

The following code is supposed to read through some numbers and put ' <== Smallest number' next to the smallest. What's my problem here? It doesn't seem to be working! Every time it seems to assign the wrong number as the minimum.
import java.util.ArrayList;
import java.util.Scanner;
public class arrayex1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter numbers: ");
for (int i = 0; i < 10; i++) {
int num = input.nextInt();
numbers.add(num);
}
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n) {
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++) {
if (n.get(i) < min) {
min = i;
}
}
return min;
}
}

if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
By calling numbers.get() you fetch the value of the slot at i.

The variable min in findMin() is actually the index of the minimum number in n.
Change this:
if (n.get(i) < min)
to:
if (n.get(i) < n.get(min))
Store the return value of findMin() before entering the for loop:
final int min_idx = findMin(numbers);
for (int i = 0; i < numbers.size(); i++) {
if (min_idx == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}

You can use collection sort method for sorting an list. Documentation
After the sort first element will be the smallest one

Here is an improved, working sample (though without the Scanner inputs for easy testing):
public static void main(String[] args){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(7);
numbers.add(3);
int minIndex = findMin(numbers);
for(int i = 0; i < numbers.size(); i++){
if(minIndex == i){ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}else{
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n){
int minValue = Integer.MAX_VALUE; // Get value at index position 0 as the current smallest.
int minIndex = -1;
for(int i = 0; i < n.size(); i++){
if(n.get(i) < minValue){
minIndex = i;
}
}
return minIndex;
}
There was some confusion as to if the findMin method returned the minimum value, or the minimum index. It now returns the minimum index. findMin is also now called only once, not for every iteration in the loop, which is a little cleaner (and slightly faster).

if (n.get(i) < min)
should be:
if (n.get(i) < n.get(min))
See it

Just change the following code and it will work for sure.
**if (numbers.get(findMin(numbers)) == numbers.get(i))**
{ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}
and
public static int findMin(ArrayList<Integer> n)
{
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++)
{
**if (n.get(i) < n.get(min))**
{
min = i;
}
}
return min;
}

You see the unexpected behavior because you don't obey the contract for List.get(). The method expects an index as argument and returns you the value. You should not compare the value returned by get() to an index.
Also, in your findMin() method you should initialize min to Integer.MAX_VALUE.

Related

How to get the multiple index of the same large numbers in an array?

I am trying to get the indices of large numbers within an array and I am having trouble doing so..
My code works if there is only one large number in the array. However, if there is one or more of the same large number, it does not works.
For example,
if I have an array {2,1,1,2,1}, it should return me the index 0 and 3 (this does not)
if I have an array {2,1,3,2,1}, it will then return me index 2. (this works)
Currently, I am trying to store the index by making use of an array, however in my code, as given in my example above, it only returns me the index of the first large number it found.
My code:
class Main {
public static void getIndexOfMax(int array[]) {
int max = array[0];
int pos = 0;
int max_index[] = new int[array.length];
int counter = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i])
{
pos = i;
max = array[i];
max_index[counter] = pos;
counter += 1;
}
}
public static void main(String[] args) {
int[] num = {2,1,1,2,1};
getIndexOfMax(num);
}
}
Thanks in advance for any replies!
You need to check another case when you find the maximum value again and store the index. And when the new maximum value starts the counter from 0 again.
public static void printIndexOfMax(int array[]) {
int max = 0;
int max_index[] = new int[array.length];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (max <= array[i]) { // Allowing same maximum number
if (max < array[i]) // Start counter from 0 when new maximum value found
counter = 0;
max = array[i];
max_index[counter] = i;
counter++;
}
}
for (int i = 0; i < counter; i++) {
System.out.println(max_index[i]);
}
}
You can have another conditional stating, if max is equal to an array element, then store that element index also. Then you would have to declare another array for the max index positions.
`if (max < array[i]) {
pos = i;
indexStorage.add(pos)
max = array[I];
max_index[counter] = pos;
counter += 1;
}`

Sorting an array by number of digits in each element from largest to smallest using loops java

I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}

Random int array not printing min and max

I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.
Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);
This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.

Find min in Arraylist of object, can't compare the elements in an arraylist

I'm trying to invoke the getScore() method in my StudentScore class to determine the min and max over elements in an ArrayList, within the printStat() method presented below. I'm getting an ArrayIndexOutOfBoundException. What does that mean, and how can I fix the problem?
public class ScoreCalculator{
private int[] scoreCounter;
ArrayList<StudentScore> scores ;
public ScoreCalculator(int maxScore) {
scoreCounter = new int[maxScore];
scores = new ArrayList<StudentScore>(maxScore);
}
public void printStat() {
System.out.println("Score Report for " + scores.size() + " Students ");
min = 0;
max = 0;
int j=0;
for ( j = 0; j < scores.size(); j++) {
if (scores.get(j).getScore() < scores.get(j - 1).getScore()) {
min = scores.get(j).getScore();
}
if (scores.get(j).getScore() > scores.get(j - 1).getScore()) {
max = scores.get(j).getScore();
}
}
System.out.println(min);
System.out.println(max);
}
If your loop starts form j=0, and you access the element at j-1 in the list, you will see where the issue is.
When j=0, you try to access -1. There is no index -1. Hence the error. Starting from j=1 solves this.
Does this help in any way?
please,
change from
for(j=0;j<scores.size();j++){
to
for(j=1;j<scores.size();j++){
You cannot find the min/max of a sequence by only comparing neighboring values.
You have to compare values to the min/max-so-far.
if (scores.isEmpty())
throw new IllegalStateException("No scores found");
int min = scores.get(0).getScore();
int max = min;
for (int j = 1; j < scores.size(); j++) {
int score = scores.get(j).getScore();
if (score < min)
min = score;
if (score > max)
max = score;
}

returning a value not working correctly? (basic Java)

In this program, I must have user input value for variable (N). In method 1, user will input 10 numbers into an array. In method 2, it will compare variable (N) and save all numbers larger than that variable to (greaterNums) variable. Having some return and sending problems, even though I have read chapter over and over. Someone please point me in the right direction!
Problem 1: greaterNums variable value isn't correct after the arguments in method 2.
Problem 2: greaterNums variable isn't returning to main method to be displayed.
import javax.swing.JOptionPane;
public class Project6Walker
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; //Establish array size
int n; //Holds comparable value
String input; //Holds user input
int[] array = new int[ARRAY_SIZE]; //Establishes array
input = JOptionPane.showInputDialog("Enter a number. Must not be a negative number.");
n = Integer.parseInt(input); //Gather value N
while (n < 0) //INPUT VALIDATION for N
{
input = JOptionPane.showInputDialog("Must not be a negative number. Please try again.");
n = Integer.parseInt(input);
}
gatherArrayInformation(array, input); //Calls method 1
compareArrayInformation(array, n); //Calls method 2
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here)."); //Final output of information
/**
This method will prompt the user to enter 10 numbers in the array
that will be compared to the value N
*/
}
public static int[] gatherArrayInformation(int[] array, String input)
{
JOptionPane.showMessageDialog(null, "Enter series of " + array.length + " numbers");
for (int i= 0; i < array.length; i++)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + ":");
array[i] = Integer.parseInt(input);
while (array[i] < 0)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + " cannot be negative. Try Again.");
array[i] = Integer.parseInt(input);
}
System.out.print(array[i] + " ");
}
return array;
}
/**
This method will take the 10 numbers from method 1,
and see which numbers are larger than N
#return greaterNums
*/
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 1; i < array.length; i++)
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
}
Problem 2: When you return greaterNums, as your code currently stands, it's just returning the array member with the highest index that was bigger than n.
Array indices start from 0.
public static List<Integer> compareArrayInformation(int[] array, int n)
{
List<Integer> greaterNums = new ArrayList<>();
for (int i = 0; i < array.length; i++) // Count from 0
{
if (array[i] > n) {
int greaterNum = array[i];
System.out.println(greaterNum);
greaterNums.add(greaterNum);
}
}
return greaterNums;
}
And to collect all greater numbers, one better uses no fixed sized array, int[], but a List<Integer>.
Replace your function compareArrayInformation to below
public static int compareArrayInformation(int[] array, int n)
{
int[] greaterNums = new int[10];
for (int i= 0; i < array.length; i++)
{
if (array[i] > n)
{
greaterNums.add(array[i]);
}
}
return greaterNums;
}
and in your main method change the below lines FROM
compareArrayInformation(array, n);
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here).");
TO
int[] greaterNumsArray = compareArrayInformation(array, n);
StringBuffer sBuffer = new StringBuffer("");
for (int i=0; i<greaterNumsArray.length; i++){
sBuffer.append(greaterNumsArray[i]);
}
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are "+sBuffer );
this program will work with i set to 0 not one but it will of course only show THE LAST GREATER NUMBER not nums hope that is what you wanted.
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
maybe you want this?
public static int[] compareArrayInformation(int[] array, int n)
{
int[] greaternums=new int[array.length];
int upto=0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaternums[upto] = array[i];
System.out.println(array[i]);
upto++;
}
return Arrays.copyOf(greaternums, upto);
}

Categories

Resources