我正在制作一个简单的应用,您必须在其中切换按钮/布尔值以尝试猜测正确的组合。我想知道最简单的方法来比较切换布尔值和“正确”组合。例如,如果用户具有:


  布尔值1:正确
  布尔值2:假
  布尔值3:真


但是正确的组合是:


  布尔值1:正确
  布尔值2:正确
  布尔值3:真


我希望用户看到一条消息,说您有3个正确的2个。我有

public void go(View view){
    if (bool1 == true && boo12 == true && bool3 == true) {
        // do this
    } else {
        // display the correct amount of booleans the user has correct.
    }
}

最佳答案

为正确的组合创建一个BitSet(设置与“ true”相对应的位,清除与“ false”相对应的位)。
当您要检查用户的输入时,请通过按下的按钮创建一个BitSet(设置为“ true”,清除“ false”)。
可以使用correctValue.equals(usersAttempt)检查正确性。
可以通过执行usersAttempt.xor(correctValue)获得计数,然后usersAttempt.cardinality()将返回错误值的数量。


这需要最少的编码量。例如:

// Correct: [true,true,true]
BitSet correct = new BitSet(3);
correct.set(0); // <= true
correct.set(1); // <= true
correct.set(2); // <= true

// User's attempt (buttonN.isChecked() is just placeholder, drop in whatever
// code you actually use to get the state of your buttons):
BitSet attempt = new BitSet(3);
attempt.set(0, button0.isChecked()); // <= true in your example
attempt.set(1, button1.isChecked()); // <= false in your example
attempt.set(2, button2.isChecked()); // <= true in your example

// Check answer (produces false in your example):
boolean matchIsPerfect = attempt.equals(correct);

// Get the count (produces 1 in your example):
attempt.xor(correct);
int incorrectCount = attempt.cardinality();

// To get the correct count just subtract 'incorrectCount' from total.

// Another way to check if attempt is correct is 'if (incorrectCount == 0)'.

// Note that the remaining bits set in 'attempt' after the above xor()
// will correspond to the individual inputs that weren't correct.


这将使您支持任何大小,代码清晰明了,您无需自己执行任何逻辑。请注意,如果您有一系列按钮,或者可以访问给定索引的用户输入,则可以简化按钮->用户的尝试设置。

09-05 08:44