Flatlyn
Flatlyn

Reputation: 2050

Collections.shuffle not working as expected

I'm trying to write a simple encryption algo that is a randomized shift pattern encryption. I've written it to be based on an array of all the characters that then uses Collections.shuffle and then matches things to that. However the array doesn't seem to be shuffling as the output text is the same as input

Here is my method

static void encrypt(String s)
    {
        //Define variable for indexOf output
        int n;

        //Encrypted output
        String output = "";

        //Shuffle array to create random replacements
        Collections.shuffle(Arrays.asList(alphashuff));

        //Create new string
        String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int index = 0; index < s.length();index++)
        {
            char aChar = s.charAt(index);
            n = alpha.indexOf(aChar, 0);

            if(n == -1)
            {
                output = output + aChar;
            }
            else
            {
                output = output + alphashuff[n];
            }

        }

        //Print encrypted string to console
        System.out.println("Encrypted Text: " + output);
    }

Upvotes: 3

Views: 3519

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You're not shuffling the array, instead a List created using the array. Create the list before sending it to shuffle:

//I'm assuming alphashuff is a char[]
List<Character> lstCh = new ArrayList<Character>();
for(char c : arrCh) {
    lstCh.add(c);
}
Collections.shuffle(lstCh);
//...
else
{
    output = output + lstCh.get(n);
}

Upvotes: 5

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

String[] alphashuff = ...;
List list = Arrays.asList(alphashuff);
Collections.shuffle(list);

This list is shuffled now which consist of values of alphashuff.

And use this like - output = output + list.get(n);

Upvotes: 1

Related Questions