Variable Alphabetics Permutation Algorithm - Simple yet mind-boggling -
i came across apparently simple problem turned out mind boggling couldn't sleep 2 days.
here problem:
a variable consist of number of characters -> $i=5. need print every possible alphabetical combination $i=2 $i=5.
the output $i=5 needs be: aa ab ac ... zz aaa aab ... zzz aaaa aaab .... zzzz aaaaa ..... zzzzz
you need use only loops or foreach or while loops achieve (no functions used) , print output each string formed instead of saving in array. please not use loop inside of loop inside of loop because $i can 100 or 200.
you can take array of alphabets 'a' 'z'. can please me out simple elegant solution this?
before loop have array aa. in loop @ array.
if array sequence of z replace contents sequence of a has length incremented 1. if new array has length larger maximum exit loop.
otherwise @ tail of array, in form xz*, x letter except z, followed 0 or more letters z. replace tail of array ya*, y letter follows x, ie. y = x + 1, , a* sequence of letters a of exact same length original sequence of letters z (remember length can zero).
in case write new contents of array output , repeat loop.
you'll need 2 loops. outer main loop prints new value in each iteration. inner loop converts z's a's.
Comments
Post a Comment