My Solution with Explanation

Hey Everyone!

I think I've found a rather short and elegant way to solve this particular problem. It prints a random letter without using substr(). Maybe it's not correct, but it seems to be working:

``````\$name = "Turd Ferguson, King of the Turds";
print \$name[rand(0,strlen(\$name))];
``````

Okay, so when I wrote this up, I figured, "Hey, all I need to do is print out a character from my name." That means the first part of the code should look like what I would type if I was trying to type a letter from a string, i.e. \$name[x].

Now, you don't want to just type out any old letter. You want to print out a random letter. So that's why we put in rand() in there. However, to make random work, you have to tell rand() a min and a max. I set the min at 0 because that's the first character of any string and then I set the max to the length of the string, i.e. strlen(\$name).

I don't know what substr was suppose to be for, but if it's supposed to be used/if this code doesn't work for y'all, please let me know.

1 vote

so,i find the solution
print substr(\$n, rand(0, strlen(\$n)), 1)

Explanation
We must find in our string random symbol which is between 0 and length of our string, but it might be only 1 symbol(its our third argument)

1 vote

I agree this can be a bit simpler. Here is what I generated and passed with

\$name = "Steve";
\$length = strlen(\$name)-1;
print \$name [rand(0, \$length)];

I tested this with only a single character and it continues to function correctly.

1 Comment

evtihii over 2 years ago

Of course, but I wanted to explain the algorithm without code.