原始问题:
小美拥有众多彩虹糖,每日尝新组合可获喜悦,她能连续几天享受此乐趣?Java求解。
以下是用Java实现的代码:
import java.util.HashSet;
public class RainbowCandy {
public static void main(String[] args) {
int[] candies = {6, 1, 1, 4, 5, 1, 4};
int happyDays = countHappyDays(candies);
System.out.println(happyDays);
}
public static int countHappyDays(int[] candies) {
HashSet<String> combinations = new HashSet<>();
int happyDays = 0;
for (int i = 0; i < candies.length; i++) {
for (int j = i + 1; j < candies.length; j++) {
String combination = candies[i] + "-" + candies[j];
if (!combinations.contains(combination)) {
combinations.add(combination);
happyDays++;
}
}
}
return happyDays;
}
}这段代码首先定义了一个countHappyDays方法,该方法接受一个整数数组作为参数,表示每颗彩虹糖的颜色。然后,使用一个HashSet来存储已经吃过的糖的组合,以便判断是否是之前没吃过的组合。
接下来,使用两层循环遍历所有可能的糖的组合。对于每一对糖,将它们的颜色组合成一个字符串,并检查该组合是否已经存在于HashSet中。如果不存在,则将该组合添加到HashSet中,并将happyDays计数器加一。
最后,返回happyDays作为结果,表示小美最多有几天会很高兴。
在main方法中,我们定义了一个示例输入数组candies,并调用countHappyDays方法计算结果并打印输出。运行代码将输出结果为3,表示小美最多有3天会很高兴。
Prev:小美与彩虹糖:探索不同组合带来的喜悦天数