Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

[Java] Randomly choosing array elements

Name: Anonymous 2011-11-24 14:22

So I have a program that generates random passwords using the ASCII values from 33 - 126, but there are certain ones I don't want to use (34, 35, 100, whatever)

What I initially did was use Math.random to generate a number between 33 - 126, then an if statement to make sure the generated password didn't contain any of the forbidden characters.

This is extremely inefficient and shitty, and I would much rather make it so I have an array of all the valid ASCII values, and it randomly chooses, say, 6 of them and throws them in to another char array to hold the password.

I am quite new at this, so I don't really know how to do that.

This is the for loop that I am currently using to pick values between 33 and 126:

for(int i = 0; i < tempPass.length; i++)
{
   tempPass[i] = (char)((int)(94 * Math.random()) + 33);
}

How do I change this to pick values from 0 to 76 (the elements of the valid char array)??

Name: Anonymous 2011-11-24 14:43

Here, OP.
#include <stdio.h>
#include <time.h>

int main(void)
{
    char values[1024];
    char evil[] = {34, 35, 100, /* whatever, */ 0};
    int i, j;
    int index = 0;
    int length = 30;    /* length of your password */

    /* seed random */
    srand(time(NULL));

    /* list possible characters from
     * 33 to 126, excluding the evil
     * ones
     */
    for(i = 33; i <= 126; i++)
    {
        values[index++] = i;
        for(j = 0; evil[j]; j++)
            if(evil[j]==i)
                --index;
    }

    /* write out the random password */
    for(i = 0; i < length; i++)
        putchar(values[rand() % index]);
   
    return 0;
}
.

BTW that's in C, not in Java.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List