Home > Software engineering >  How to get the smallest number of an array with the exception of sentinel value?
How to get the smallest number of an array with the exception of sentinel value?

Time:09-24

I made a code, my only problem is that it displays the sentinel value (zero) as its smallest number.

How do I ignore the sentinel value when taking the smallest number?

for (int c = 0; c < lengthOfArray; c  ) {
    if(arr[c] < min)
        min = arr[c];             
             
    if (arr[c] > max)
       max = arr[c];      
}
             
System.out.println("Smallest:");
System.out.println(min);
System.out.println("Largest:");
System.out.println(max);

Below is my expected output:

(input:)
1 5 3 0

(output:)
Smallest:
 1
Largest:
5

However, my current code would always display 0 (zero) in the Smallest.

CodePudding user response:

Solution

You may add a condition on the value along woth min one :

if (arr[c] < min && arr[c] != 0)

Improve

You can iterate on values and not in index, code may be nicer :

int[] arr = new int[]{8, 6, 9, 0, 6, 8};
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

for (int val : arr) {
    if (val < min && val != 0)
        min = val;
    if (val > max)
        max = val;
}

System.out.println("Smallest: "   min); // Smallest: 6
System.out.println("Largest:"   max); // Largest:9

CodePudding user response:

just add an condition

for (int c = 0; c < lengthOfArray; c  ) {
  if(arr[c] != 0){

    if(arr[c] < min)
        min = arr[c];             
             
    if (arr[c] > max)
       max = arr[c];  

   }
}
             
System.out.println("Smallest:");
System.out.println(min);
System.out.println("Largest:");
System.out.println(max);

CodePudding user response:

There is another approach for solve your problem:

    IntSummaryStatistics arrSummaryStatistics = IntStream.of(arr)
            .summaryStatistics();

    System.out.println("Smallest:");
    System.out.println(arrSummaryStatistics.getMin());
    System.out.println("Largest:");
    System.out.println(arrSummaryStatistics.getMax());

CodePudding user response:

Another variant using IntStream and OptionalInt:

int[] nums = {1, 5, 3, 0};
OptionalInt min = IntStream.of(nums).filter(x -> x != 0).min();
OptionalInt max = IntStream.of(nums).filter(x -> x != 0).max();
  •  Tags:  
  • java
  • Related