0

I am trying to create an app with a String password, that all it does, is iterate through all possible combination of Chars and numbers until hits the correct one, something like that:

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();
            }
        }
    });


}
}

How should I approach it?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Dgot
  • 119
  • 3
  • 14

1 Answers1

0

Most common approach for this type of problem is permutations with repetition.

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]);
        }
    }
}
  1. String[] elements is array of characters used in passwd.
  2. int lenghtOflist is password length.

Check this answer

Community
  • 1
  • 1
MackTank
  • 183
  • 9