在Java中优化If-else If-else语句
在执行乐透检查程序时,其中一个约束条件是不使用循环或数据结构(如数组、列表等)我编写了以下代码,以检查用户给出的3个条目(draw1、draw2、draw3)是否等于程序生成的7个随机数中的任何一个(随机1,随机2,随机3,…)在Java中优化If-else If-else语句,java,if-statement,optimization,logic,Java,If Statement,Optimization,Logic,在执行乐透检查程序时,其中一个约束条件是不使用循环或数据结构(如数组、列表等)我编写了以下代码,以检查用户给出的3个条目(draw1、draw2、draw3)是否等于程序生成的7个随机数中的任何一个(随机1,随机2,随机3,…) 我该如何进行优化,最重要的是,优化只会增加可读性,还是会提高程序的效率?使用集合,这将提高可读性 Set<Integer> luckyNumbers = new HashSet<>(); //Add your numbers to
我该如何进行优化,最重要的是,优化只会增加可读性,还是会提高程序的效率?使用集合,这将提高可读性
Set<Integer> luckyNumbers = new HashSet<>();
//Add your numbers to the set
//Integer i = ...
//luckyNumbers.add(i);
Set<Integer> drawNumbers = new HashSet<>();
//Integer i = ...
//drawNumbers.add(i);
Set<Integer> matchNumbers = new HashSet<>(luckyNumbers);
matchNumbers.retainAll(drawNumbers);
//In matchNumbers will be the intersection of the previous sets.
//There you can get the size of the intersection set or its content to show the
//matches
试试这个
static boolean equalsAny(int base, int... comparisons) {
for (int c : comparisons)
if (base == c)
return true;
return false;
}
你可以重写
if (random1 == draw1 || random2 == draw1 || random3 == draw1 || random4 == draw1 || random5 == draw1
|| random6 == draw1 || random7 == draw1) {
到
是否允许使用本机方法,如
ArrayList.contains(…)
?将随机数放入一个集合,将抽签数放入另一个集合,然后找到交叉点的大小。很抱歉,我现在编辑了这个问题。我们不允许使用任何数据结构,因此不允许使用集合、数组或列表。如果您不使用循环或数据结构,如set
,您将编写7^3=343
pif-else
块的置换。我想你不想这样做。为什么我要写343个if-else块的置换?我很困惑。我们不应该使用循环!而且,我以前没有提到过(对不起!)但我们也不允许使用集合或列表之类的数据结构。老实说……告诉你的教授,这太愚蠢了,不会教你在职业生涯中任何时候都需要的任何东西。除非你想成为一名教授;)
static boolean equalsAny(int base, int... comparisons) {
for (int c : comparisons)
if (base == c)
return true;
return false;
}
if (random1 == draw1 || random2 == draw1 || random3 == draw1 || random4 == draw1 || random5 == draw1
|| random6 == draw1 || random7 == draw1) {
if (equalsAny(draw1, random1, random2, random3, random4, random5, random6, random7)) {