This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Functions, Part I Forum

View Course » View Exercise

1289 points
Picture
Submitted by
Chris
over 1 year ago

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

permalink

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)

612 points
53805ce498a6423b7c8e819af3083a08?s=140&d=retro
Submitted by
evtihii
over 1 year ago


1 vote

permalink

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.

276 points
71561a50833386872fa9bca137ea463c?s=140&d=retro
Submitted by
Steve
over 1 year ago

1 Comment

53805ce498a6423b7c8e819af3083a08?s=140&d=retro evtihii over 1 year ago

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