-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.php
executable file
·118 lines (98 loc) · 2.38 KB
/
test.php
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
#!/usr/bin/php
<?php
const PROD = 0;
const DEBUG = 1;
/**
* Created by PhpStorm.
* User: heiko
* Date: 31.07.17
* Time: 09:00
*/
if (sizeof($argv) !== 2) {
echo "ERROR: Invalid parameter nr - only one parameter (sample-size) is allowed" . PHP_EOL;
return;
}
elseif (!filter_var($argv[1], FILTER_VALIDATE_INT)) {
echo "ERROR: Supplied sample size must be of type int" . PHP_EOL;
return;
}
$sampleSize = (int)$argv[1];
$sampler = new StreamSampler($sampleSize, DEBUG);
//$sample = new StreamSampler($sampleSize, PROD);
$sampler->work();
class StreamSampler {
/**
* nr of chars to sample
*/
private $sampleSize;
/**
* nr of chars already sampled
*/
private $sampled;
/**
* the current char to be processed
*/
private $currentChar;
/**
* the actual sample as an array of chars
*/
private $sample;
/**
* 1 = DEBUG, 0 = PROD
*/
private $mode;
public function __construct($sampleSize, $mode = PROD) {
$this->sampleSize = $sampleSize;
$this->mode = $mode;
$this->currentChar = null;
$this->sampled = 0;
$this->sample = [];
}
/**
*
*/
public function work() {
while($line = fgets(STDIN)){
$this->processLine($line);
}
$sampleString = implode($this->sample);
echo "Random Sample: $sampleString" . PHP_EOL;
}
public function processLine($line) {
$lineLength = strlen($line);
for ($i = 0; $i < $lineLength; $i++) {
$this->currentChar = $line[$i];
++$this->sampled;
$this->processChar();
}
}
private function processChar() {
// if we dont have a full sample yet, we add unconditionally
if (sizeof($this->sample) < $this->sampleSize) {
$this->addCurrentChar();
return;
}
$addProb = $this->computeAddProb();
$doAdd = mt_rand(0, 1) <= $addProb;
$charAdded = null;
$charRemoved = null;
if ($doAdd) {
$charRemoved = $this->removeRandOne();
$charAdded = $this->addCurrentChar();
}
}
private function computeAddProb() {
// the probabilty of an element being in a a subset of (n choose k) is:
return 1/2;
}
private function addCurrentChar() {
$this->sample[] = $this->currentChar;
return $this->currentChar;
}
private function removeRandOne() {
$key = array_rand($this->sample);
unset($this->sample[$key]);
return $key;
}
}
?>