我正在尝试创建一个带有字符串密码的应用程序,它所做的就是迭代所有可能的字符和数字组合,直到找到正确的密码,就像这样:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PasswordDetector extends AppCompatActivity {
private static final String PASSWORD = "abc123";
private Button search;
private EditText combination;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//here I want the loop to run, untill it hits the PASSWORD
combination.setText("combinations");
if (combination.getText().toString().equals(PASSWORD)) {
Toast.makeText(PasswordDetector.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
}
}
我该如何接近它?
答案 0 :(得分:0)
此类问题的最常见方法是重复排列。
unittest {
struct S(A...) {}
static assert(is(S!(QName!"com.example"[0..$-1]) == S!(QName!"com")));
static assert(is(S!(QName!"com.example", QName!"mail") == S!(QName!"com.example.mail")));
static assert(is(S!(QName!"com"[0..$-1]) == S!(QName!"")));
}
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else {
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++){
for(int j = 0; j < allSublists.length; j++){
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main(String[] args){
String[] database = {"a","b","c"};
for(int i=1; i<=database.length; i++){
String[] result = getAllLists(database, i);
for(int j=0; j<result.length; j++){
System.out.println(result[j]);
}
}
}
是passwd中使用的字符数组。String[] elements
是密码长度。