简体   繁体   English

用方法参数找到数组最小值的优雅方法?

[英]Elegant way to find min of an array using method parameters?

I'm looking for an elegant way to express this pseudo code. 我正在寻找一种表达此伪代码的优雅方法。 For my assignment, I cannot change the method signature or parameter type. 对于我的任务,我无法更改方法签名或参数类型。

    private static int smallest(int... nums)
    {
        return Arrays.stream(nums).min().getAsInt();
    }

All I'm trying to do is take a huge varying list of ints as a parameter from the method call and return the smallest int of all the int parameters. 所有我想要做的是采取INTS的巨大变化的列表,从方法调用的参数和返回所有的int参数的最小INT。 I've tried to google and read the API to find out how to correctly implement this, but I've gotten only this far. 我已经尝试通过Google搜索并阅读了API,以了解如何正确实现此目的,但到目前为止,我还没有做过。 Can someone help me syntactically correct this to compile and output correctly? 有人可以在语法上帮助我正确地进行编译和输出吗?

I cannot correctly post my console errors with formatting, so I'm posting it as an update to my OP. 我无法正确发布带有格式的控制台错误,因此我将其作为OP的更新发布。 To answer @Marvin I'm getting this error in my compiler... 回答@Marvin我在编译器中遇到此错误...

Methods1.java:25: error: cannot find symbol
  int small = Arrays.stream(nums).min().getAsInt();
              ^
symbol:   variable Arrays
location: class Methods1
1 error

You almost had it, it's getAsInt() instead of get() : 您几乎拥有了它,它是getAsInt()而不是get()

private static int smallest(int... nums) {
    return Arrays.stream(nums).min().getAsInt();
}

Complete working sample on ideone.com : ideone.com上的完整工作示例

import java.util.Arrays;

class Ideone {
    public static void main (String[] args) {
        int[] nums = new int[] { 7, -2, 5, 12 };
        System.out.println(smallest(nums));
    }

    private static int smallest(int... nums) {
        return Arrays.stream(nums).min().getAsInt();
    }
}

Prints: 印刷品:

-2

You could iterate over the whole array like this 您可以像这样遍历整个数组

private static int smallest(int[] array)
{
    //check if the array is empty
    if(array.length == 0)
    {
        //handle, whatever happens if the array is empty
        return -1; //maybe you should throw an exception here 
    }

    //storing the smallest found value, start with the first int in the array
    int smallest = array[0];

    //the iteration
    for(int i : array)
    {
        //check if the current checked value is smaller than the smallest found...
        if(i < smallest)
        {
            //...and if it is, set it as the smallest found value
            smallest = i;
        }
    }
    //finally, return the smallest value
    return smallest;
}

This should solve your current problem, but in most cases i'd rather recommend to use a pre sorted array or list instead. 这应该可以解决您当前的问题,但是在大多数情况下,我宁愿建议使用预排序数组或列表。 If the data in it is already stored in ascending order, the first element would always be the lowest and the last element always the highest value. 如果数据已按升序存储,则第一个元素将始终是最低值,最后一个元素将始终是最高值。

This method takes an infinite unknown variable quantity of parameters by using varargs as it's argument. 此方法通过使用varargs作为参数来获取无限数量的未知可变参数。 Combining all the parameters added from it's call from main into an array of the same type. 将从main调用添加的所有参数组合到相同类型的数组中。 This was designed to account for mutability of the original method call in main. 这是为了解决main中原始方法调用的可变性而设计的。 Finally, returning the smallest integer of all the parameters. 最后,返回所有参数的最小整数。

I'm a fairly new programmer, second year into computer science, and I'm not sure if this is even useful for anyone, but I hope it helps. 我是一个相当新的程序员,计算机科学专业的第二年,我不确定这是否对任何人都有用,但是我希望它会有所帮助。 Thanks to everyone here for your awesome tips and error catches. 感谢这里的所有人提供的出色提示和错误捕获。 My issue was I forgot to import my Array class and one of my method calls from stream class was incorrectly named. 我的问题是我忘记了导入Array类,而流类中的方法调用之一被错误命名。

Lastly, for any veteran programmers out there, aside from this looking snappy and elegant, does this statement execute any faster than doing a simple foreach loop and comparing the num to the last smallest one? 最后,对于那些经验丰富的资深程序员,除了看起来活泼而优雅之外,此语句的执行速度是否比执行简单的foreach循环并将num与最后一个最小的比较的执行速度还快?

   import java.util.Arrays;

   public class Test
   {
       public static void main(String[] args)
       {
           // Enter as many as you want here, can be more or less than three
           int num1 = 23;
           int num2 = 89;
           int num3 = 9;

           // Apply each variable as an argument for the method call
           int smallestNumber = smallest(num1, num2, num3);
           // Print out variable value to prove it works
           System.out.print(smallestNumber);
       }

       private static Integer smallest(int... nums)
       {
           // Found an elegant way to do the stubbed out block of code
           // I left the code down there to show what is going on here
           try
           {
               return Arrays.stream(nums).min().getAsInt();
           }
           catch (Exception e)
           {
               return null;
           }


           // The above code is essentially doing the below code
           /*try
           {
               // Initialize Variable to start of array
               int smallest = nums[0];

               // For:Each Loop: go through each parameter and assign it a local variable to compare with
               for(int i : nums)
               {
                   // compare if smaller
                   if(i < smallest)
                   {
                       // If true, set as smallest
                       smallest = i;
                   }
               }
               return smallest;
           }
           catch (Exception e)
           {
               return null;
           }*/
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM