gpt4 book ai didi

java - 执行 "max"的功能方法(使用递归/不使用可变变量)

转载 作者:行者123 更新时间:2023-12-03 23:11:44 24 4
gpt4 key购买 nike

使用命令式代码在未排序的数组中查找最大值非常简单

例如在Java中(我相信它可以写得更好,仅用于说明目的)

public class Main {
public static void main(String[] args) {
int[] array = {1,3,5,4,2};
int max = findMax(array);
System.out.println(max);
}

public static int findMax(int[] array){
int max = Integer.MIN_VALUE; //or array[0], but it requires a null check and I want to keep it simple :)
for (int i = 0, size = array.length; i < size ; i++) {
int current = array[i];
if(current > max) max = current;
}
return max;
}
}

这样做的功能方法是什么?例如

  • 没有可变变量(例如,使 max 在 Scala 中成为 val/在 Java 中成为 final)
  • 没有循环(例如使用递归,tail 首选)

在 Scala 的源代码中我看到它是使用 recudeLeft 完成的,这看起来很聪明

  def max[B >: A](implicit cmp: Ordering[B]): A = {
if (isEmpty)
throw new UnsupportedOperationException("empty.max")

reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
}

但假设我没有(出于某种原因)reduce/reduceLeft 可用/已实现(并且由于某种原因我不想/不能实现它,即我正在使用纯 Java)

在不依赖其他函数方法的情况下,“惯用”函数方法是什么(例如,我将如何在简单的 Java 中实现它,但要牢记函数范例)

答案可以使用任何语言(但首选 Java/Scala)

最佳答案

这是一个带有最大值累加器的尾调用递归实现。

public class Main {

public static void main(String[] args) {
System.out.println(max(new int[]{6, 3, 9, 4}));
}

public static int max(int[] ints) {
return max(ints, Integer.MIN_VALUE);
}

public static int max(int[] ints, int max) {
if (ints.length == 0) {
return max;
} else {
return max(Arrays.copyOfRange(ints, 1, ints.length), ints[0] > max ? ints[0] : max);
}
}

}

关于java - 执行 "max"的功能方法(使用递归/不使用可变变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com