Safe Cracking. PHP Style





  • Or, he could have gone the complex route and just iterated over the numbers in the array n times - without PHP, although I do give bonus points for figuring our a way to get a browser to do this for you!



  • Er.

    There are, what, 24 possible combinations here?

    Oh, by the way, when people say "Always seed the random number generator before you use it", that's not what they mean.


    There's some really dreadful code in the documentation comments, but I can't believe a moderator let that shit through.



  • "
    What would be the proper way of writing this code?  Obviously my
    'brute-force' method of running a random sequence an extreme amount of
    times does work and yields what i think is the correct number of
    combinations, but there must be a more efficient method?"

    He's ASKING for a better way, not saying it's the right way.



  • Yeah, but not only does his algo suck, his implementation sucks.  If he used the string as an array key instead of  a value, you could illiminate the call to array_unique() and use 99% less memory.  And you don't need to seed the RNG every time you call rand().

    That being said, here's my crappy 2-minute implementation (I'm know there was a more clever way to do it w/o all the array copies.  I chose this only for ease of implementation):
    $arr = array(12 => 12, 18 => 18, 24 => 24, 36 => 36);
    foreach($arr as $num) {
      $arr_cp = $arr;
      unset($arr_cp[$num]);
      foreach($arr_cp as $inner_num) {
        $arr_cp2 = $arr_cp;
        unset($arr_cp2[$inner_num]);
        foreach($arr_cp2 as $last_num) {
          echo "$num-$inner_num-$last_num\n";
        }
      }
    }
    /
    12-18-24
    12-18-36
    12-24-18
    12-24-36
    12-36-18
    12-36-24
    18-12-24
    18-12-36
    18-24-12
    18-24-36
    18-36-12
    18-36-24
    24-12-18
    24-12-36
    24-18-12
    24-18-36
    24-36-12
    24-36-18
    36-12-18
    36-12-24
    36-18-12
    36-18-24
    36-24-12
    36-24-18
    /



  • When I was first learning to program at age 13 (using C), I was trying to find a value in a 2d array. I figured the computer was fast, so I'd just generate random indexes into the array until it came up with a hit. Needless to say, it didn't work.

    I asked my dad for help, and he explained the joys of nested for loops. lol.



  • I guess I missed part of the problem, which actually makes it even easier -- I didn't allow a number to show up in the combination more than once.  I'm pretty sure he's actually allowing for that, in which case my implementation shortens to:

    $arr = array(12,18,24,36);
    foreach($arr as $num)
      foreach($arr as $inner_num)
        foreach($arr as $last_num)
          echo "$num-$inner_num-$last_num\n";


Log in to reply