1

currently im working on a game and I'm progressing quite well.
The problem is my shuffle algorithm. A word should be shuffled with randomness
but MUST NOT shuffled in its original wordform. Example: "table" -> "table"
I want something like this: "table" -> "tlabe"

The first and last letter should stay at its place but the rest can be shuffled randomly except to its original wordform.

Currently i am using this function i wrote:

function shuffle_word($word)
{
    if(strlen($word) < 2)
        return $word;
    else
        return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
}

You can check out my game so far and get a better idea of it:
WordShuffle - The Game

(Sorry the words are german at the moment, because I am german and testing it with friends make it easier)

MrDarkLynx
  • 686
  • 1
  • 9
  • 15
  • What is the problem? – jeroen Feb 17 '17 at 13:47
  • Store the shuffled word in a variable and compare it to your `$word`. If they are the same, shuffle again. – MrDarkLynx Feb 17 '17 at 13:48
  • The word often shuffles in its original wordform. I dont want that, it musnt happen otherwise there is nothing to guess. –  Feb 17 '17 at 13:48
  • Obvious first problem might be that you're shuffling bytes, not characters; nor do you have any checking to see if the shuffle has returned the same order of bytes – Mark Baker Feb 17 '17 at 13:49
  • @MrDarkLynx that sounds very helpful and simple. Thanks i will test it –  Feb 17 '17 at 13:49
  • And of course if the original word was __3__ characters long, then the middle character could never be shuffled to a different position – Mark Baker Feb 17 '17 at 13:50

2 Answers2

0

A simpler way to do it would be to split all the characters using str_split, then shuffle the obtained array using the shuffle function then implode the array and you got your word shuffled !
Sample code:

function shuffle_word($word) {
   $chars = str_split($word);
   shuffle($chars);
   if(implode("", $chars) == $word) return shuffle_word($word);
   return implode("", $chars);
}

Have a nice day

Ad5001
  • 748
  • 5
  • 19
0

Thank you guys for the fast answers. I fixed the algorithm by checking in a while loop if the shuffled word is equal to the non shuffled word.