我正在尝试在 Java8 中编写 FizzBu​​zz 问题。它工作正常,我得到了想要的输出。对于可被“3”整除的数,应返回“Fizz”,对于可被“5”整除的数,应返回“Buzz”,对于可被两者整除的数,应返回“FizzBu​​zz”。

如果我将值传递为“15”,它将返回:

["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

现在,我被困在一件事上。如果我将值传递为“15”,我想获得如下输出:
{"Fizz": [3, 6, 9, 12],"Buzz": [5, 10],"FizzBuzz": [15]}

我想按 Fizz、Buzz 和 FizzBu​​zz 对数字进行分组。

这是我的代码:
public class FizzBuzzService {

private Map<Rule, String> ruleContainers = new HashMap();
private Set<Rule> rules  = new HashSet();

public FizzBuzzService(){
    addRule(i -> i % 15 == 0, "FizzBuzz");
    addRule(i -> i % 3 == 0, "Fizz");
    addRule(i -> i % 5 == 0, "Buzz");
}

public void addRule(Rule rule, String res) {
    rules.add(rule);
    ruleContainers.put(rule, res);
}

public String getValue(int i) {
    for (Rule rule : rules) {
        if (rule.apply(i)) {
            return ruleContainers.get(rule);
        }
    }
    return String.valueOf(i);
}

//then the origin code should be as follows:
public List<String> fizzBuzz(int n) {
     List<String> res = new ArrayList();
     for(int i = 1; i <= n; i++){
         res.add(getValue(i));
     }
     return res;
 }

interface Rule{
    boolean apply(int i);
}
}

如果有人可以指导我,我将不胜感激。谢谢

最佳答案

我会返回一个 Map<String, List<Integer>> (使用 LinkedHashMap 而不是 HashMap 并且您的键将保留插入顺序)为 List<Integer>fizzbuzz 值创建 fizzbuzz (s)。它可以在单个 static 方法中完成,例如,

public static Map<String, List<Integer>> fizzBuzz(int n) {
    Map<String, List<Integer>> map = new HashMap<>();
    List<Integer> fizz = new ArrayList<>(), //
            buzz = new ArrayList<>(), //
            fizzbuzz = new ArrayList<>();
    IntStream.rangeClosed(1, n).forEachOrdered(i -> {
        boolean f = i % 3 == 0, b = i % 5 == 0;
        if (f && b) {
            fizzbuzz.add(i);
        } else if (f) {
            fizz.add(i);
        } else if (b) {
            buzz.add(i);
        }
    });
    map.put("Fizz", fizz);
    map.put("Buzz", buzz);
    map.put("FizzBuzz", fizzbuzz);
    return map;
}

关于java - FizzBu​​zz 数字的分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48354492/

10-09 19:35