-2

I need to build strings in PHP with every possible combination like

s5z-s4z-s3z-s2z-s1z

where the 's' then the number are always in the same position. the only difference is whether there is a z on the end or not.

So for example I would have

  • s5z-s4z-s3z-s2z-s1
  • s5z-s4z-s3z-s2z-s1z
  • s5z-s4z-s3z-s2-s1
  • s5z-s4z-s3z-s2z-s1
  • s5z-s4z-s3z-s2-s1z
  • s5z-s4z-s3-s2-s1z
  • etc.

How would I go about doing that?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Blade
  • 51
  • 1
  • 5
  • Please re-tag your question as "homework". Also, it's a dup of: http://stackoverflow.com/questions/2617055/how-to-generate-all-permutations-of-a-string-in-php – Nir Alfasi Sep 06 '12 at 20:52
  • duplicate of homework? that's... lame(lame()).. – Moe Tsao Sep 06 '12 at 20:54
  • @MoeTsao I guess the OP doesn't understand that he won't have access to SO during the final exam... :) – Nir Alfasi Sep 06 '12 at 20:56
  • @alfasin What if he does? Should we setup a "test_question" tag? Advise all school teachers to monitor this during programming language test? We can then tag it with the community's force – Moe Tsao Sep 06 '12 at 21:00

1 Answers1

3

So basically it all relies on "is the z there or not". This can easily be translated to a binary number, where each 0 represents the z not being there, and each 1 indicated the presence of the z.

As a result, you need only loop through all the numbers.

$length = 5;
$max = bindec(str_repeat("1",$length));
$out = Array();
for( $i=0; $i<$max; $i++) {
  $entry = Array();
  for( $x=0; $x<$length; $x++) $entry[] = "s".($length-$x).($i & (1<<$x) ? "z" : "");
  $out[] = implode("-",$entry);
}
echo implode(" ",$out);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks! I tried all sorts of things and could not get it. thank you very much for this. – Blade Sep 06 '12 at 23:58