GridManager.php 19.2 KB
Newer Older
arnaudbey's avatar
add app  
arnaudbey committed
1 2 3 4 5
<?php

namespace  MagicWordBundle\Manager;

use JMS\DiExtraBundle\Annotation as DI;
arnaudbey's avatar
arnaudbey committed
6
use LexiconBundle\Entity\Language;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
7 8 9
use LexiconBundle\Entity\Word;
use LexiconBundle\Entity\WordStart;
use MagicWordBundle\Entity\Grid;
arnaudbey's avatar
add app  
arnaudbey committed
10 11 12 13 14 15 16 17 18
use Symfony\Component\HttpFoundation\Request;

/**
 * @DI\Service("mw_manager.grid")
 */
class GridManager
{
    protected $em;
    protected $squareManager;
Arnaud Bey's avatar
Arnaud Bey committed
19
    protected $languageManager;
arnaudbey's avatar
add app  
arnaudbey committed
20 21 22 23 24 25 26 27
    protected $foundableFormManager;
    protected $tokenStorage;

    /**
     * @DI\InjectParams({
     *      "entityManager"         = @DI\Inject("doctrine.orm.entity_manager"),
     *      "foundableFormManager"  = @DI\Inject("mw_manager.foundableform"),
     *      "squareManager"         = @DI\Inject("mw_manager.square"),
Arnaud Bey's avatar
Arnaud Bey committed
28
     *      "languageManager"       = @DI\Inject("lexicon_manager.language"),
arnaudbey's avatar
add app  
arnaudbey committed
29 30 31
     *      "tokenStorage"          = @DI\Inject("security.token_storage"),
     * })
     */
Arnaud Bey's avatar
Arnaud Bey committed
32
    public function __construct($entityManager, $foundableFormManager, $squareManager, $languageManager, $tokenStorage)
arnaudbey's avatar
add app  
arnaudbey committed
33 34 35 36
    {
        $this->em = $entityManager;
        $this->foundableFormManager = $foundableFormManager;
        $this->squareManager = $squareManager;
Arnaud Bey's avatar
Arnaud Bey committed
37
        $this->languageManager = $languageManager;
arnaudbey's avatar
add app  
arnaudbey committed
38 39 40
        $this->tokenStorage = $tokenStorage;
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
41
    private function newGrid($language, $side)
arnaudbey's avatar
add app  
arnaudbey committed
42 43 44
    {
        $grid = new Grid();
        $grid->setLanguage($language);
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
45
        $grid->setSide($side);
arnaudbey's avatar
add app  
arnaudbey committed
46 47 48 49

        return $grid;
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
50

Sylvain Hatier's avatar
Sylvain Hatier committed
51
    public function generate(Language $language, $debug = false, $minBigram = null)
arnaudbey's avatar
add app  
arnaudbey committed
52
    {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
53
        $grid = $this->newGrid($language, 4);
Arnaud Bey's avatar
Arnaud Bey committed
54

Sylvain Hatier's avatar
Sylvain Hatier committed
55 56
        $minBigram = ($minBigram == null) ? $language->getMinBigram() : $minBigram;
        $letters = $this->lottery($language, 4, $debug, $minBigram);
57 58 59 60 61 62 63 64

        if ($debug === true) {
            echo "\nletters: ";
            foreach ($letters as $letter) {
                echo $letter;
            }
            echo "\n";
        }
arnaudbey's avatar
add app  
arnaudbey committed
65 66

        foreach ($letters as $letter) {
Sylvain Hatier's avatar
Sylvain Hatier committed
67 68
            $square = $this->squareManager->create($letter, $grid);
            $grid->addSquare($square);
arnaudbey's avatar
add app  
arnaudbey committed
69
        }
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
70 71
        $words = $this->findWords($grid);
        $this->foundableFormManager->populateFoundables($words, $grid);
arnaudbey's avatar
add app  
arnaudbey committed
72 73 74 75

        return $grid;
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
76

arnaudbey's avatar
add app  
arnaudbey committed
77 78 79
    public function createGrid($request, $save)
    {
        $languageId = $request->request->get('language');
arnaudbey's avatar
arnaudbey committed
80
        $language = $this->em->getRepository('LexiconBundle:Language')->find($languageId);
arnaudbey's avatar
add app  
arnaudbey committed
81

82
        $grid = $this->newGrid($language, 4);
arnaudbey's avatar
add app  
arnaudbey committed
83 84 85
        $this->addSquares($grid, $request->request->get('squares'));

        if ($save) {
86
            $grid = $this->saveFoundables($grid);
arnaudbey's avatar
add app  
arnaudbey committed
87 88 89 90 91 92 93 94
        }

        return $grid;
    }

    public function updateGrid(Grid $grid, Request $request, $round)
    {
        $grid->setLanguage($round->getLanguage());
95 96
        $this->removeSquares($grid);

arnaudbey's avatar
add app  
arnaudbey committed
97 98 99 100 101
        $this->removeFoundables($grid);

        $this->em->refresh($grid);

        $this->addSquares($grid, $request->request->get('squares'));
102
        $grid = $this->saveFoundables($grid);
arnaudbey's avatar
add app  
arnaudbey committed
103 104 105 106 107 108 109

        $this->em->persist($grid);
        $this->em->flush($grid);

        return $grid;
    }

110
    public function saveFoundables(Grid $grid)
arnaudbey's avatar
add app  
arnaudbey committed
111 112
    {
        $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
113
        $inflections = $this->findWords($grid);
arnaudbey's avatar
add app  
arnaudbey committed
114 115 116 117 118 119 120 121
        $this->foundableFormManager->populateFoundables($inflections, $grid);

        $this->em->persist($grid);
        $this->em->flush();

        return $grid;
    }

122
    private function removeSquares(Grid $grid)
arnaudbey's avatar
add app  
arnaudbey committed
123 124 125 126 127 128
    {
        $squares = $grid->getSquares();
        foreach ($squares as $square) {
            $this->em->remove($square);
        }
        $this->em->flush();
129 130

        return;
arnaudbey's avatar
add app  
arnaudbey committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    }

    private function removeFoundables(Grid $grid)
    {
        $foundables = $grid->getFoundableForms();
        foreach ($foundables as $foundable) {
            $this->em->remove($foundable);
        }

        $this->em->flush();
    }

    private function addSquares(Grid $grid, $letters)
    {
        foreach ($letters as $letter) {
            $grid->addSquare($this->squareManager->create(strtolower($letter), $grid));
        }

        return $grid;
    }

    public function getInflections(Request $request)
    {
        $grid = $this->createGrid($request, false);
155
        $inflections = $this->findWords($grid);
arnaudbey's avatar
add app  
arnaudbey committed
156 157 158 159 160 161 162

        return $inflections;
    }

    public function getFoundableForms(Request $request)
    {
        $grid = $this->createGrid($request, false);
163
        $inflections = $this->findWords($grid);
arnaudbey's avatar
add app  
arnaudbey committed
164 165 166 167 168 169

        $this->foundableFormManager->populateFoundables($inflections, $grid);

        return $grid->getFoundableForms();
    }

170
    public function getCombos($words)
arnaudbey's avatar
add app  
arnaudbey committed
171 172
    {
        $combos = [];
173 174 175 176 177 178 179 180 181 182
        foreach ($words as $word) {
            $root = $word->getRoot();
            $form = $word->getCleanValue();
            $rootId = $root->getId();

            if (!isset($combos[$rootId])) {
                $combos[$rootId] = [
                    'root' => [
                        'id' => $rootId,
                        'value' => $root->getValue(),
arnaudbey's avatar
add app  
arnaudbey committed
183
                    ],
184
                    'words' => [],
arnaudbey's avatar
add app  
arnaudbey committed
185 186 187
                ];
            }

188 189
            if (!in_array($form, $combos[$rootId]['words'])) {
                $combos[$rootId]['words'][] = $form;
arnaudbey's avatar
add app  
arnaudbey committed
190 191 192 193
            }
        }

        $combos = array_filter($combos, function ($v) {
194
            return count($v['words']) > 1;
arnaudbey's avatar
add app  
arnaudbey committed
195 196 197
        });

        usort($combos, function ($a, $b) {
198
            return count($b['words']) - count($a['words']);
arnaudbey's avatar
add app  
arnaudbey committed
199 200 201 202 203
        });

        return $combos;
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
204
    public function findWords(Grid $grid)
arnaudbey's avatar
add app  
arnaudbey committed
205 206
    {
        $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
207
        $side = $grid->getSide();
arnaudbey's avatar
add app  
arnaudbey committed
208
        $i = 0;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
209 210
        $simplifiedGrid = [];
        $wordStarts = [];
arnaudbey's avatar
add app  
arnaudbey committed
211 212
        $this->currentLanguage = $grid->getLanguage();

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
213 214 215 216 217
        // on créé un tableau plus simple à manipuler.
        for ($y = 0; $y < $side; ++$y) {
            for ($x = 0; $x < $side; ++$x) {
                $simplifiedGrid[$y][$x] = ($grid->getSquares()[$i])
                  ? $grid->getSquares()[$i]->getLetter()->getValue()
Arnaud Bey's avatar
Arnaud Bey committed
218
                  : null;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
219

arnaudbey's avatar
add app  
arnaudbey committed
220 221 222 223 224
                ++$i;
            }
        }

        // on l'alimente par récursivité avec la méthode nextLetter() en partant de chaque lettre
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
225 226
        for ($y = 0; $y < $side; ++$y) {
            for ($x = 0; $x < $side; ++$x) {
arnaudbey's avatar
add app  
arnaudbey committed
227
                // ajout au tableau des mots potentiels de ceux qui commencent par la lettre en x, y
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
228
                $wordStarts = array_unique(array_merge($wordStarts, $this->nextLetter('', $simplifiedGrid, $x, $y, $side)), SORT_STRING);
arnaudbey's avatar
add app  
arnaudbey committed
229 230
            }
        }
Arnaud Bey's avatar
Arnaud Bey committed
231 232


arnaudbey's avatar
add app  
arnaudbey committed
233 234
        // words contient tous les débuts de mots ayant été trouvé dans le dictionnaire
        // il faut vérifier si chaque word existe réellement dans le dictionnaire
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
235 236 237

        if ($wordStarts) {
            return $this->em->getRepository(Word::class)->getExistingWords($wordStarts, $this->currentLanguage);
arnaudbey's avatar
add app  
arnaudbey committed
238 239
        }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
240
        return [];
arnaudbey's avatar
add app  
arnaudbey committed
241 242
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
243 244

    private function nextLetter($word, $grid, $x, $y, $side)
arnaudbey's avatar
add app  
arnaudbey committed
245 246 247 248 249
    {
        $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
        // ajouter la lettre en x, y au mot courant
        $word .= $grid[$y][$x];
        // la détruire dans la grille
Arnaud Bey's avatar
Arnaud Bey committed
250
        $grid[$y][$x] = null;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
251

252
        $wordLongEnough = mb_strlen($word) > 1;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
253 254 255

        if ($wordLongEnough) {
            // vérifier en bdd s'il existe des mots qui commencent par $word à partir de 2 lettres
Arnaud Bey's avatar
Arnaud Bey committed
256 257 258 259 260
            // $startExists = $this->em->getRepository(WordStart::class)->search($word, $this->currentLanguage->getId());
            $startExists = $this->em->getRepository(WordStart::class)->findOneBy([
                "value" => $word,
                "language" => $this->currentLanguage
            ]);
arnaudbey's avatar
add app  
arnaudbey committed
261 262
            // si pas de mot dans le dico commençant par le mot en cours, ne pas retourner le mot et arrêter la recherche
            if (!$startExists) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
263
                return [];
arnaudbey's avatar
add app  
arnaudbey committed
264 265 266
            }
        }
        // stocker le début de mot dès qu'il atteint 2 lettres
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
267
        $words = $wordLongEnough ? array($word) : [];
arnaudbey's avatar
add app  
arnaudbey committed
268 269 270 271

        //
        // On calcule la position de la lettre suivante (autour de la lettre en cours)
        //
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
272
        // ligne du dessus
arnaudbey's avatar
add app  
arnaudbey committed
273 274 275 276
        $yy = $y - 1;
        if ($yy >= 0) {
            $xx = $x - 1;
            // on vérifie que la lettre n'a pas été utilisée (donc détruite)
Arnaud Bey's avatar
Arnaud Bey committed
277
            if (($xx >= 0) && ($grid[$yy][$xx] != null)) {
arnaudbey's avatar
add app  
arnaudbey committed
278
                // appel en récursif pour ajout d'une nouvelle lettre au mot
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
279
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
280 281 282
            }

            $xx = $x;
Arnaud Bey's avatar
Arnaud Bey committed
283
            if ($grid[$yy][$xx] != null) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
284
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
285 286 287
            }

            $xx = $x + 1;
Arnaud Bey's avatar
Arnaud Bey committed
288
            if (($xx < $side) && ($grid[$yy][$xx] != null)) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
289
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
290 291 292
            }
        }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
293
        // ligne courante
arnaudbey's avatar
add app  
arnaudbey committed
294 295
        $yy = $y;
        $xx = $x - 1;
Arnaud Bey's avatar
Arnaud Bey committed
296
        if (($xx >= 0) && ($grid[$yy][$xx] != null)) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
297
            $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
298 299
        }
        $xx = $x + 1;
Arnaud Bey's avatar
Arnaud Bey committed
300
        if (($xx < $side) && ($grid[$yy][$xx] != null)) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
301
            $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
302 303
        }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
304
        // ligne du dessous
arnaudbey's avatar
add app  
arnaudbey committed
305
        $yy = $y + 1;
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
306
        if ($yy < $side) {
arnaudbey's avatar
add app  
arnaudbey committed
307
            $xx = $x - 1;
Arnaud Bey's avatar
Arnaud Bey committed
308
            if (($xx >= 0) && ($grid[$yy][$xx] != null)) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
309
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
310 311 312
            }

            $xx = $x;
Arnaud Bey's avatar
Arnaud Bey committed
313
            if ($grid[$yy][$xx] != null) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
314
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
315 316 317
            }

            $xx = $x + 1;
Arnaud Bey's avatar
Arnaud Bey committed
318
            if (($xx < $side) && ($grid[$yy][$xx] != null)) {
Arnaud Bey's avatar
WIP  
Arnaud Bey committed
319
                $words = array_merge($words, $this->nextLetter($word, $grid, $xx, $yy, $side));
arnaudbey's avatar
add app  
arnaudbey committed
320 321 322 323 324 325 326
            }
        }

        // renvoyer les débuts de mot trouvés
        return $words;
    }

Arnaud Bey's avatar
WIP  
Arnaud Bey committed
327

arnaudbey's avatar
add app  
arnaudbey committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    public function retrieveInflections(Grid $grid)
    {
        $inflections = [];
        $foundables = $grid->getFoundableForms();
        foreach ($foundables as $foundable) {
            foreach ($foundable->getInflections() as $inflection) {
                $inflections[] = $inflection;
            }
        }

        return $inflections;
    }

    public function export(Grid $grid = null)
    {
        if ($grid) {
            $gridJSON = [
                'language' => $grid->getLanguage()->getId(),
                'letters' => [],
            ];

            foreach ($grid->getSquares() as $square) {
                $gridJSON['letters'][] = $square->getLetter()->getValue();
            }

            return $gridJSON;
        }

        return;
    }
358

Sylvain Hatier's avatar
Sylvain Hatier committed
359
    public function lottery(Language $language, $side, $debug = false, $minBigram = null)
360
    {
Sylvain Hatier's avatar
Sylvain Hatier committed
361
        $minBigram = ($minBigram == null) ? $language->getMinBigram() : $minBigram;
362 363
        // On crée un tableau de bigrammes
        // où chaque bigramme apparait autant de fois que son poids
Arnaud Bey's avatar
Arnaud Bey committed
364 365 366 367 368 369
        // Modif: on  garde les $minBigram pourcent les plus productifs des bigrammes
        // Génération d'un tableau qui a chaque bigram associe le % de bigram moins fréquents (centile)
        $centilesBigrams = [];
        $poidsBigrams = [];
        $bigramsToFreq = [];
        $nbBigrams=0;
Arnaud Bey's avatar
Arnaud Bey committed
370
        $lines = $this->languageManager->getBigrams($language);
371 372 373 374
        array_shift($lines);
        foreach ($lines as $line) {
            $tab = explode("\t", $line);
            $string = $tab[0];
Sylvain Hatier's avatar
Sylvain Hatier committed
375
            $freqBigramBi = $tab[1];
376
            $poids = $tab[3];
Arnaud Bey's avatar
Arnaud Bey committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
            $nbBigrams++;
            $bigramsToFreq[$string]=$freqBigramBi;
            $poidsBigrams[$string]=$freqBigramBi;
        }
        asort($bigramsToFreq);
        $nbInferiorBigram=0;
        $bigrams = [];
        // $lines = $this->languageManager->getBigrams($language);
        $lettersFromBigrams=[];
        // array_shift($lines);
        foreach ($bigramsToFreq as $bigramToFreq => $value) {
            $nbInferiorBigram++;
            $centile = 100 - intval(($nbBigrams-$nbInferiorBigram)*100/$nbBigrams);
            $centilesBigrams[$bigramToFreq]=$centile;
            //file_put_contents("data/log_bigram.txt", $bigramToFreq."\t".$centile."\n", FILE_APPEND);
            if ($centilesBigrams[$bigramToFreq] >= $minBigram) {
                $bigramLetters = preg_split('//u', $bigramToFreq, null, PREG_SPLIT_NO_EMPTY);
Sylvain Hatier's avatar
Sylvain Hatier committed
394 395 396 397
                foreach ($bigramLetters as $bigramLetter) {
                    $lettersFromBigrams[$bigramLetter] = 1;
                }

Arnaud Bey's avatar
Arnaud Bey committed
398 399
                for ($j = 0; $j < $poidsBigrams[$bigramToFreq]; $j++) {
                    $bigrams[] = $bigramToFreq;
Sylvain Hatier's avatar
Sylvain Hatier committed
400
                }
401 402
            }
        }
Arnaud Bey's avatar
Arnaud Bey committed
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        $countsBigram = array_count_values($bigrams);
        // var_dump($countsBigram);
        // die();
        // // On initialise une grille vide.
        $grid = [];
        for ($i=0; $i < $side; $i++) {
            for ($j=0; $j < $side; $j++) {
                $grid[$i][$j] = null;
            }
        }

        $emptySquares = $this->getEmptySquares($grid, $side);
        //tant qu'il reste des cases vides
        while (!empty($emptySquares)) {
            $bigram = $bigrams[array_rand($bigrams)];
            $emptySquare = $emptySquares[array_rand($emptySquares)];
            $emptySquareI = $emptySquare[0];
            $emptySquareJ = $emptySquare[1];

            $chars = preg_split('//u', $bigram, -1, PREG_SPLIT_NO_EMPTY);
            $firstLetter = $chars[0];
            $secondLetter = $chars[1];
            $flagBigram = false;
            // on regarde si une lettre du bigram pioché est déjà présente et qu'elle a des adjacent vide.
            for ($i=0; $i < $side; $i++) {
                for ($j=0; $j < $side; $j++) {
                    if ($grid[$i][$j] == $firstLetter) {
                        $ajdacentsLetterBigram = $this->getAdjacentSquares($grid, $side, [$i, $j], true);
                        if (!empty($ajdacentsLetterBigram)) {
                            $ajdacentLetterBigram = $ajdacentsLetterBigram[array_rand($ajdacentsLetterBigram)];
                            $grid[$ajdacentLetterBigram[0]][$ajdacentLetterBigram[1]] = $secondLetter;
                            $flagBigram = true;
                            break 2;
                        }
                    } elseif ($grid[$i][$j] == $secondLetter) {
                        $ajdacentsLetterBigram = $this->getAdjacentSquares($grid, $side, [$i, $j], true);
                        if (!empty($ajdacentsLetterBigram)) {
                            $ajdacentLetterBigram = $ajdacentsLetterBigram[array_rand($ajdacentsLetterBigram)];
                            $grid[$ajdacentLetterBigram[0]][$ajdacentLetterBigram[1]] = $firstLetter;
                            $flagBigram = true;
                            break 2;
                        }
                    }
                }
            }
            if (!$flagBigram) {
                $ajdacentEmptySquares = $this->getAdjacentSquares($grid, $side, $emptySquare, true);

                if (empty($ajdacentEmptySquares)) {
                    $ajdacentSquares = $this->getAdjacentSquares($grid, $side, $emptySquare, false);
                    $letterToScore=[];
                    foreach ($lettersFromBigrams as $key => $value) {
                        $score=0;
                        foreach ($ajdacentSquares as $ajdacentSquare) {
                            $letter = $grid[$ajdacentSquare[0]][$ajdacentSquare[1]];
                            if (isset($countsBigram[$letter.$key])) {
                                $score += $countsBigram[$letter.$key];
                            } elseif (isset($countsBigram[$key.$letter])) {
                                $score += $countsBigram[$key.$letter];
                            }
                        }
                        $letterToScore[$key] = $score;
                    }
                    arsort($letterToScore);
                    reset($letterToScore);
                    $bestLetter = key($letterToScore);
                    $grid[$emptySquareI][$emptySquareJ] = $bestLetter;
                } else {
                    $randomAdjacent = $ajdacentEmptySquares[array_rand($ajdacentEmptySquares)];
                    $grid[$emptySquareI][$emptySquareJ] = $firstLetter;
                    $grid[$randomAdjacent[0]][$randomAdjacent[1]] = $secondLetter;
                }
            }
            $emptySquares = $this->getEmptySquares($grid, $side);
        }

        $letters = [];
        for ($i=0; $i < $side; $i++) {
            for ($j=0; $j < $side; $j++) {
                $letters[] = $grid[$i][$j];
            }
        }
        return $letters;
    }

    private function getAdjacentSquares($grid, $side, $square, $returnEmpty = true)
    {
        $emptyAdjacentSquares = [];
        $i = $square[0];
        $j = $square[1];

        $left = $i - 1;
        $right = $i + 1;
        $top = $j - 1;
        $bottom = $j + 1;

        $lookLeft = ($left >= 0) ? true : false;
        $lookTop = ($top >= 0) ? true : false;
        $lookRight = ($right < $side) ? true : false;
        $lookBottom = ($bottom < $side) ? true : false;

        if ($lookTop) {
            if ($lookLeft && $grid[$top][$left] === null) {
                $emptyAdjacentSquares[] = [$top, $left];
            } elseif ($lookLeft) {
                $adjacentSquares[] = [$top, $left];
            }


            if ($grid[$top][$j] === null) {
                $emptyAdjacentSquares[] = [$top, $j];
            }
            $adjacentSquares[] = [$top, $j];
            if ($lookRight && $grid[$top][$right] === null) {
                $emptyAdjacentSquares[] = [$top, $right];
            } elseif ($lookRight) {
                $adjacentSquares[] = [$top, $right];
            }
        }

        if ($lookRight && $grid[$i][$right] === null) {
            $emptyAdjacentSquares[] = [$i, $right];
        } elseif ($lookRight) {
            $adjacentSquares[] = [$i, $right];
        }


        if ($lookBottom) {
            if ($lookRight && $grid[$bottom][$right] === null) {
                $emptyAdjacentSquares[] = [$bottom, $right];
            } elseif ($lookRight) {
                $adjacentSquares[] = [$bottom, $right];
            }
            $adjacentSquares[] = [$bottom, $j];
            if ($grid[$bottom][$j] === null) {
                $emptyAdjacentSquares[] = [$bottom, $j];
            }
            if ($lookLeft && $grid[$bottom][$left] === null) {
                $emptyAdjacentSquares[] = [$bottom, $left];
            } elseif ($lookLeft) {
                $adjacentSquares[] = [$bottom, $left];
            }
        }

        if ($lookLeft && $grid[$i][$left] === null) {
            $emptyAdjacentSquares[] = [$i, $left];
        } elseif ($lookLeft) {
            $adjacentSquares[] = [$i, $left];
        }


        return ($returnEmpty) ? $emptyAdjacentSquares : $adjacentSquares;
    }

    private function getEmptySquares($grid, $side)
    {
        $emptySquares = [];

        for ($i=0; $i < $side; $i++) {
            for ($j=0; $j < $side; $j++) {
                if ($grid[$i][$j] === null) {
                    $emptySquares[] = [$i, $j];
                }
            }
        }

        return $emptySquares;
    }
arnaudbey's avatar
add app  
arnaudbey committed
572
}