IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Voir le flux RSS

phpiste

Un script qui ne sert à rien

Noter ce billet
par , 23/09/2016 à 14h35 (670 Affichages)
Voici un petit bout de code Php qui ne serve à rien sauf qu'il détecte des similarities dans un tableau

enfaite c'était un chalenge personnel pour détecter des lettres similaires dans un tableau selon différentes stratégies.

Nom : Screen Shot 2016-09-23 at 1.29.19 PM.png
Affichages : 1018
Taille : 79,5 Ko

Les défis aussi était de pouvoir ajouter facilement une stratégie, Une stratégie de recherche de similarité n'est qu'un couple x/y des différentes combinaisons possibles de recherche

Exemple de strategies knight, plus, plus_and_coin;

Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
$directions = [ 
    'knight' => [[2, 1],[2, -1],[-2, 1],[-2, -1],[1, 2],[-1,2],[1,-2],[-1,-2]], 
    // pour la lettre a par exemple
    //a b c
    //b a v
    //c a b
    'plus' => [[0, 1],[-1, 0],[0, -1],[1, 0]], 
    'plus_and_coin' => [[0, 1],[-1, 0],[0, -1],[1, 0],[1, 1],[-1, 1],[1, -1],[-1, -1]] 
];

sinon voici le code source de l'exemple ainsi le demo

la method getRegularConnexion permet au script de s'arrêter une fois un nombre limite de connexions qui répondent a la stratégie est atteint
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
 
<?php
 
/**
 * Copyright (c) <2015>, Ghali Ahmed<ghaliano2005@gmail.com>
 *
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This class find similarity for given cel on 2D array
 * the search strategie can be easly modified with the given direction
 * @Exemple: when the given direction array is: [[0, 1],[-1, 0],[0, -1],[1, 0]]
 * the script will look recursively to the right, top, bottom, left, right of the given cel
 * @author Ghali Ahmed<ghaliano2005@gmail.com>
 * @version 1.0
 */
class MathMatrixHelper
{
    protected $atomes = [];
 
    protected $tile = [];
 
    protected $visited = [];
 
    protected $tileDim = 20;
 
    private $maxNest;
 
    /**
     * Direction to find friend cell
     */
    protected $directions = [];
 
    public function __construct($atomes, $directions, $tileDim)
    {
        $this->atomes = $atomes;
        $this->directions = $directions;
        $this->tileDim = $tileDim;
        $this->maxNest = ini_set('xdebug.max_nesting_level', 0);
        $this->init();
    }
 
    public function init()
    {
        $i = 0;
        while ($i < $this->tileDim) {
            $j = 0;
            $this->tile[$i] = [];
            while ($j < $this->tileDim) {
                $this->tile[$i][$j] = $this->atomes[array_rand($this->atomes)];
                $this->visited[$i][$j] = [];
                $j++;
            }
            $i++;
        }
    }
 
    public function getAllConnexion($i, $j, &$result = [])
    {
        foreach ($this->directions as $key => $direction) {
            $iTarget = $i + $direction[0];
            $jTarget = $j + $direction[1];
 
            if (isset($this->tile[$iTarget][$jTarget])) {
                if (($this->tile[$i][$j] == $this->tile[$iTarget][$jTarget])
                    && !isset($this->visited[$i][$j][$key])
                    && !isset($this->visited[$iTarget][$jTarget][$key])) {
                    $result[] = "$i:$j";
                    $this->visited[$i][$j][$key] = true;
 
                    $this->getAllConnexion($iTarget, $jTarget, $result);
                }
            }
        }
 
        return $result;
    }
 
    /**
     * Search for connexion in regular mode until there length reached the max value
     * @var $m x0
     * @var $n y0
     */
    public function getRegularConnexion($m, $n, $max, $onlyFirst=false) 
	{
		$result = [];
		$len = count($this->tile);
		foreach ($this->directions as $key => $direction) {
			if (!isset($result[$key])) {
				$result[$key] = [];
			} 
			for ($i = 0; $i < $len; $i++) {
				$iTarget = $m + $i*$direction[0];
				$jTarget = $n + $i*$direction[1];
					if ($this->tile[$m][$n] != @$this->tile[$iTarget][$jTarget]) {
					break;
				} else {
					$result[$key][] = "$iTarget:$jTarget";
					if ($onlyFirst && (count($result[$key]) == $max)) {
						return $result[$key];
					}
				}
			}
            if (!$onlyFirst && count($result[$key]) <$max) {
                $result[$key] = [];
            }
		};
 
		return $this->flatten($result);
	}
 
    /**
     * Print array like a matrix
     * and display connexion with special color
     */
    public function printTile($result, $m, $n)
    {
        $linePattern = "[%s]<br />";
        $itemPattern = "%s<span style='%s'>%s</span>";
        $output = "";
        for ($i = 0; $i<$this->tileDim; $i++) {
            $sep = '';
            $j = 0;
            $str = '';
            for ($j = 0; $j<$this->tileDim; $j++) {
                $in = in_array("$i:$j", $result);
                $from = $i == $m && $j == $n;
                $str .= sprintf($itemPattern, $sep, ($in ? 'color: red; font-weight: bold;' : '').($from ? 'border: 1px solid;' : ''), @$this->tile[$i][$j]);
                $sep = ',';
            }
            $output .= sprintf($linePattern, $str);
        }
 
        print '<pre>'.$output.'</pre>';
    }
 
    public function __destruct()
    {
        if (!empty($this->maxNest)) {
            ini_set('xdebug.max_nesting_level', $this->maxNest);
        }
    }
 
    /**
     * Thnaks to http://stackoverflow.com/users/28835/too-much-php
     * http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array
     */
    protected function flatten(array $array) 
    {
        $return = array();
        array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
 
        return $return;
    }
}

Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
<?php
include('matrix.php');
 
$letters = ['a', 'b', 'c', 'd'];
$directions = [
	'knight' => [[2, 1],[2, -1],[-2, 1],[-2, -1],[1, 2],[-1,2],[1,-2],[-1,-2]],
	'plus' => [[0, 1],[-1, 0],[0, -1],[1, 0]],
	'plus_and_coin' => [[0, 1],[-1, 0],[0, -1],[1, 0],[1, 1],[-1, 1],[1, -1],[-1, -1]]
];
 
$strategie = 'plus_and_coin';
 
$matrix = new MathMatrixHelper($letters, $directions[$strategie], 20);
print '<b>getAllConnexion:</b><br>';
$startTime = microtime(true);
$result = $matrix->getAllConnexion(6, 6);
$matrix->printTile($result, 6, 6);
 
print '<b>getRegularConnexion:</b><br>';
$result = $matrix->getRegularConnexion(6, 6, 5, true);
$matrix->printTile($result, 6, 6);
$endTime = microtime(true);
echo "Execution time : " . ($endTime - $startTime) . " seconds<br/><br/>";

Envoyer le billet « Un script qui ne sert à rien » dans le blog Viadeo Envoyer le billet « Un script qui ne sert à rien » dans le blog Twitter Envoyer le billet « Un script qui ne sert à rien » dans le blog Google Envoyer le billet « Un script qui ne sert à rien » dans le blog Facebook Envoyer le billet « Un script qui ne sert à rien » dans le blog Digg Envoyer le billet « Un script qui ne sert à rien » dans le blog Delicious Envoyer le billet « Un script qui ne sert à rien » dans le blog MySpace Envoyer le billet « Un script qui ne sert à rien » dans le blog Yahoo

Mis à jour 17/08/2017 à 14h18 par Malick (Ajout balises code)

Catégories
PHP , Développement Web

Commentaires