SlideShare a Scribd company logo
PHP と
乱打舞図
2014/03/15
第5回 闇PHP勉強会
do_aki
@do_aki
http://do-aki.net/
title was born from typo
らんだまいず
乱打舞図
モテカルロ法っぽくない?
randomize
• 無秩序に並び替えること
• 規則性がないこと
• 偏りがないこと
http://nmi.jp/archives/541
(http://www.lauradhamilton.com/random-
lessons-online-poker-exploit)
Php radomize
randomize function in php
shuffle
str_shuffle
give it try (php 5.5.10)
function bench($name, $suffle_func) {
$result = [];
for ($i=0; $i<60000;++$i) {
$a = range(1, 3);
$suffle_func($a);
$r = implode('', $a);
$result[$r]=isset($result[$r])? $result[$r]+1 : 1;
}
print "{$name}¥n";
ksort($result);
print_r($result);
}
shuffle / str_shuffle
bench("shuffle", "shuffle");
bench("str_shuffle", function(&$ary) {
$str = str_shuffle(implode('', $ary));
$ary = str_split($str, 1);
});
result of shuffle
shuffle
Array
(
[123] => 9873
[132] => 10104
[213] => 9999
[231] => 9944
[312] => 9998
[321] => 10082
)
result of str_shuffle
str_shuffle
Array
(
[123] => 9956
[132] => 9928
[213] => 10080
[231] => 9969
[312] => 10149
[321] => 9918
)
No Problem
(in current
version of php)
過去の shuffle は等分散ではなかった
implementation of shuffle(current version)
long n_elems, rnd_idx, n_left;
char temp;
/* The implementation is stolen from array_data_shuffle */
/* Thus the characteristics of the randomization are the same */
n_elems = len;
if (n_elems <= 1) { return; }
n_left = n_elems;
while (--n_left) {
rnd_idx = php_rand(TSRMLS_C);
RAND_RANGE(rnd_idx, 0, n_left, PHP_RAND_MAX);
if (rnd_idx != n_left) {
temp = str[n_left];
str[n_left] = str[rnd_idx];
str[rnd_idx] = temp;
}
}
ext/standard/string.c より抜粋 / shuffle の実装も同じ
implementation of shuffle (php < 4.3.0)
PHP_FUNCTION(shuffle){
zval *array;
if (zend_parse_parameters(1 TSRMLS_CC, "a", &array) == FAILURE){
RETURN_FALSE;
}
if (zend_hash_sort(Z_ARRVAL_PP(&array),
(sort_func_t)php_mergesort, array_data_shuffle, 1 TSRMLS_CC) ==
FAILURE) {
RETURN_FALSE;
}
RETURN_TRUE;
}
}
static int array_data_shuffle(const void *a, const void *b
TSRMLS_DC) {
return (php_rand(TSRMLS_C) % 2) ? 1 : -1;
}
_人人人人人人人人人人人人_
> ランダムマージソート <
 ̄Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y ̄
implementation of str_shuffle (php < 4.3.0)
PHP_FUNCTION(str_shuffle)
{
/* Note : by using current php_string_shuffle for string */
/* with 6 chars (6! permutations) about 2/3 of them are */
/* computed for 6! calls for the function. So it isn't so */
/* unique. The ratio is the same for other lengths. */
char *str;
int i, str_len;
i = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str,
&str_len) == FAILURE) {
RETURN_FALSE;
}
zend_qsort((void *)str, str_len, sizeof(char), php_string_shuffle TSRMLS_CC);
RETURN_STRINGL(str, str_len, 1);
}
implementation of str_shuffle
(php < 4.3.0)
static int php_string_shuffle(const void *a,
const void *b TSRMLS_DC)
{
long rnd;
rnd = php_rand(TSRMLS_C);
if (rnd % 3)
return 1;
else if (rnd % 5)
return 0;
else
return -1;
}
_人人人人人人人人人人人人人人人_
> ランダム(?) クイックソート <
 ̄Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y ̄
emulate old shuffle (php)
bench("old_shuffle", function(&$ary){
usort($ary, function($a, $b) {
return (rand() % 2) ? 1 : -1;
});
});
bench("old_str_shuffle", function(&$ary){
usort($ary, function($a, $b) {
$rnd = rand();
if ($rnd % 3) {
return 1;
} elseif ($rnd % 5) {
return 0;
} else {
return -1;
}
});
});
result
old_shuffle
Array
(
[123] => 22358
[132] => 7627
[213] => 3771
[231] => 3827
[312] => 7487
[321] => 14930
)
old_str_shuffle
Array
(
[123] => 30982
[132] => 4453
[213] => 5994
[231] => 2928
[312] => 8979
[321] => 6664
)
現在の shuffle は、本当に問題ないのか?
php_rand(C) := rand (php)
random in php
rand
mt_rand
rand vs mt_rand
• rand
– libc の random or lrand48 or rand
– environment dependent
• mt_rand
– Mersenne Twister (MT19937)
– implementation dependent
re-imprement of shuffle
(environment independent)
function mt_shuffle(&$ary) {
$n = count($ary);
while(--$n) {
$rnd_idx = mt_rand(0, $n);
if ($rnd_idx != $n) {
$tmp = $ary[$n];
$ary[$n] = $ary[$rnd_idx];
$ary[$rnd_idx] = $tmp;
}
}
}
Conclusion
• 現在の shuffle / str_shuffle は、均等に分配
される
• 異なる環境での再現性が必要なら mt_rand
つかって再実装しよう
• php 4 はオワコン
End Of Slide
Let’s enjoy PHP hack life ;-)

More Related Content

ODP
Embedding perl
PDF
CS50 Lecture3
ODP
Отладка в GDB
PPT
Евгений Крутько, Многопоточные вычисления, современный подход.
ODP
The bones of a nice Python script
DOCX
Dns server clients (actual program)
PDF
Arduino coding class
PDF
Regexp Master
Embedding perl
CS50 Lecture3
Отладка в GDB
Евгений Крутько, Многопоточные вычисления, современный подход.
The bones of a nice Python script
Dns server clients (actual program)
Arduino coding class
Regexp Master

What's hot (19)

PPTX
Basic C++ 11/14 for Python Programmers
PDF
Top 10 pieges php afup limoges
PDF
c programming
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
KEY
Advanced Shell Scripting
PDF
start_printf: dev/ic/com.c comstart()
PDF
Hacking parse.y (RubyKansai38)
PPT
Buffer OverFlow
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
PDF
C++ L05-Functions
PDF
Hacking Parse.y with ujihisa
PDF
VTU DSA Lab Manual
PDF
C++の話(本当にあった怖い話)
PPTX
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
PPTX
Reverse Engineering: C++ "for" operator
PDF
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
PPTX
Keypoints c strings
PDF
FizzBuzz Trek
Basic C++ 11/14 for Python Programmers
Top 10 pieges php afup limoges
c programming
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Advanced Shell Scripting
start_printf: dev/ic/com.c comstart()
Hacking parse.y (RubyKansai38)
Buffer OverFlow
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
C++ L05-Functions
Hacking Parse.y with ujihisa
VTU DSA Lab Manual
C++の話(本当にあった怖い話)
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Reverse Engineering: C++ "for" operator
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Keypoints c strings
FizzBuzz Trek
Ad

More from do_aki (20)

PPTX
Tritonn から Elasticsearch への移行話
PPTX
php-src の歩き方
PPTX
PHP と SAPI と ZendEngine3 と
PPTX
PHPとシグナル、その裏側
PPTX
再考:列挙型
PPTX
signal の話 或いは Zend Signals とは何か
PPTX
PHP AST 徹底解説(補遺)
PPTX
PHP AST 徹底解説
PPTX
Writing php extensions in golang
PPTX
php7's ast
PPTX
N対1 レプリケーション + Optimizer Hint
PPTX
20150212 プレゼンテーションzen
PPTX
MySQL Casual Talks 7 「N:1 レプリケーション ~進捗どうですか?~」
PPTX
20141017 introduce razor
PPTX
20141011 mastering mysqlnd
PPTX
php in ruby
PPTX
PHP から Groonga を使うにはこんなコードになるよ!
PPTX
N:1 Replication meets MHA
PPTX
php and sapi and zendengine2 and...
PPTX
セキュアそうでセキュアじゃない少しセキュアな気分になれるmysql_config_editor
Tritonn から Elasticsearch への移行話
php-src の歩き方
PHP と SAPI と ZendEngine3 と
PHPとシグナル、その裏側
再考:列挙型
signal の話 或いは Zend Signals とは何か
PHP AST 徹底解説(補遺)
PHP AST 徹底解説
Writing php extensions in golang
php7's ast
N対1 レプリケーション + Optimizer Hint
20150212 プレゼンテーションzen
MySQL Casual Talks 7 「N:1 レプリケーション ~進捗どうですか?~」
20141017 introduce razor
20141011 mastering mysqlnd
php in ruby
PHP から Groonga を使うにはこんなコードになるよ!
N:1 Replication meets MHA
php and sapi and zendengine2 and...
セキュアそうでセキュアじゃない少しセキュアな気分になれるmysql_config_editor
Ad

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Understanding_Digital_Forensics_Presentation.pptx
Electronic commerce courselecture one. Pdf
Network Security Unit 5.pdf for BCA BBA.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Programs and apps: productivity, graphics, security and other tools
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development

Php radomize