【问题标题】:Is there a proper algorithm for concatenating strings in a way that multiple strings can be concatenated only in unique combos?是否有适当的算法来连接字符串,使得多个字符串只能以唯一的组合连接?
【发布时间】:2021-09-04 13:41:41
【问题描述】:

所以前提是我有 7 个描述符或品质,我必须询问用户每个品质与其他品质相比有多重要。所以,如果我有 7 个品质,为了方便起见,我称它们为 1-7,我需要做这样的事情......

1 - 2
1 - 3

1 - 4

1 - 5

1 - 6

1 - 7

然后随着我们继续前进,第一个数字应该从列表中剔除,现在只有 2 和其余数字之间的 5 次比较。然后这一直持续到最后剩下的要比较的数字是 6-7。这使总比较数达到 21。

我已经制定了一种可行的方法,但可能会让我成为我试图向其展示的任何工作面试的笑柄。我是一名一年级程序员,试图通过这些副项目快速找到工作,所以请理解,我知道这可能很糟糕,但我不确定最好的方法。

这是我的代码,你会改变什么? questions 变量是一个 ArrayList 以及 results 变量。谢谢。

 public void makeQuestions(){
        for (int i = 0; i < 6; i++){
            questions.add("How do you rate " + results.get(0) + " in importance compared to "+ results.get(i+1));
        }
        for (int i = 1; i < 6; i++){
            questions.add("How do you rate " + results.get(1) + " in importance compared to "+ results.get(i+1));
        }
        for (int i = 2; i < 6; i++){
            questions.add("How do you rate " + results.get(2) + " in importance compared to "+ results.get(i+1));
        }
        for (int i = 3; i < 6; i++){
            questions.add("How do you rate " + results.get(3) + " in importance compared to "+ results.get(i+1));
        }
        for (int i = 4; i < 6; i++){
            questions.add("How do you rate " + results.get(4) + " in importance compared to "+ results.get(i+1));
        }
        questions.add("How do you rate " + results.get(5) + " in importance compared to "+ results.get(6));
    }

【问题讨论】:

    标签: java algorithm loops arraylist


    【解决方案1】:

    这是一个双 for 循环的好地方:

    for (int i = 0; i < questions.size(); i++) {
        for (int j = i + 1; j < questions.size(); j++) {
            // Compare question i against question j
        }
    }
    

    【讨论】:

    • 这是一个很好的答案。我不知道为什么我没有想到这一点。谢谢。
    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2015-10-14
    • 2012-02-02
    • 1970-01-01
    • 2023-01-12
    • 2013-04-18
    相关资源
    最近更新 更多