-
Notifications
You must be signed in to change notification settings - Fork 0
/
onp.php
601 lines (516 loc) · 15.5 KB
/
onp.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<?php
abstract class Struct
{
protected $buffer = array();
public function __toString()
{
return implode(' ', $this->buffer);
}
public function size()
{
return count($this->buffer);
}
public function isEmpty()
{
return $this->size() == 0;
}
}
class Stack extends SplStack
{
public function popMultiple($cnt)
{
if ($cnt > $this->count()) {
throw new InvalidArgumentException(
sprintf("Can't pop %d elements from datastructure with %d elements", $cnt, $this->count())
);
}
$arg = array();
while ($cnt--) {
$arg[] = $this->pop();
}
return $arg;
}
}
class Queue extends Struct
{
public function enqueue($val)
{
$this->buffer[] = $val;
}
public function dequeue()
{
return array_shift($this->buffer);
}
}
class Token
{
public $type;
public $value;
public function __construct($type, $value)
{
$this->type = $type;
$this->value = $value;
}
public function __toString()
{
return (string)$this->value;
}
}
class Number extends Token
{
public function __construct($value)
{
$this->value = $this->normalize($value);
$this->type = 'number';
}
private function normalize($value)
{
//$value = str_replace(',', '.', $value);
return floatval($value);
}
}
class Coma extends Token
{
public function __construct($value)
{
parent::__construct('coma', $value);
}
}
class Bracket extends Token
{
}
class L_bracket extends Bracket
{
public function __construct($value)
{
parent::__construct('l_bracket', $value);
}
}
class R_bracket extends Token
{
public function __construct($value)
{
parent::__construct('r_bracket', $value);
}
}
abstract class Operator extends Token
{
public function __construct($value)
{
$this->value = $value;
$this->type = 'operator';
}
abstract public function priority();
abstract public function associativity();
abstract public function execute($arg);
public function numOfArgs()
{
return 2;
}
}
class PlusOperator extends Operator
{
public function priority()
{
return 2;
}
public function associativity()
{
return 'both';
}
public function execute($arg)
{
return new Number($arg[0]->value + $arg[1]->value);
}
}
class MinusOperator extends Operator
{
public function priority()
{
return 2;
}
public function associativity()
{
return 'left';
}
public function execute($arg)
{
return new Number($arg[0]->value - $arg[1]->value);
}
}
class MultiplyOperator extends Operator
{
public function priority()
{
return 3;
}
public function associativity()
{
return 'both';
}
public function execute($arg)
{
return new Number($arg[0]->value * $arg[1]->value);
}
}
class DivideOperator extends Operator
{
public function priority()
{
return 3;
}
public function associativity()
{
return 'left';
}
public function execute($arg)
{
if ($arg[1]->value == 0) {
throw new Exception('Divide by zero');
}
return new Number($arg[0]->value / $arg[1]->value);
}
}
class PowerOperator extends Operator
{
public function priority()
{
return 4;
}
public function associativity()
{
return 'right';
}
public function execute($arg)
{
return new Number(pow($arg[0]->value, $arg[1]->value));
}
}
abstract class Funct extends Token
{
public function __construct($value)
{
$this->value = $value;
$this->type = 'function';
}
abstract public function execute($arg);
abstract public function numOfArgs();
}
class SinFunction extends Funct
{
public function numOfArgs()
{
return 1;
}
public function execute($arg)
{
return new Number(sin($arg[0]->value));
}
}
class CosFunction extends Funct
{
public function numOfArgs()
{
return 1;
}
public function execute($arg)
{
return new Number(cos($arg[0]->value));
}
}
class TgFunction extends Funct
{
public function numOfArgs()
{
return 1;
}
public function execute($arg)
{
return new Number(tan($arg[0]->value));
}
}
class CtgFunction extends Funct
{
public function numOfArgs()
{
return 1;
}
public function execute($arg)
{
return new Number(tan(M_PI / 2 - $arg[0]->value));
}
}
class MaxFunction extends Funct
{
public function numOfArgs()
{
return 2;
}
public function execute($arg)
{
return new Number(max($arg[0]->value, $arg[1]->value));
}
}
abstract class Constant extends Number
{
public function __construct($value)
{
$this->value = $value;
$this->type = 'constant';
}
public function execute()
{
return new Number($this->value);
}
}
class PIConstant extends Constant
{
public function __construct($value)
{
parent::__construct(M_PI);
}
}
class EConstant extends Constant
{
public function __construct($value)
{
parent::__construct(M_E);
}
}
class Tokenizer implements Iterator
{
private $expression;
private $registeredTokens = array();
private $tokenObjs = array();
private $iPointer = 0;
public function __construct($expr)
{
$this->expression = $expr;
$this->expression = preg_replace('/\\s+/i', '$1', $this->expression);
$this->expression = strtr($this->expression, '{}[]', '()()');
if (empty($this->expression)) {
throw new Exception('Expression to tokenize is empty');
}
}
private function tokenFactory($token, $value)
{
if (!isset($this->registeredTokens[$token['type']])) {
throw new Exception("Undefined token type '{$token['type']}'");
}
$className = $token['type'] . $token['classSuffix'];
$obj = new $className($value);
return $obj;
}
public function tokenize()
{
while (strlen($this->expression) > 0) {
$isMatch = false;
foreach ($this->registeredTokens as $token) {
$regexp = "/^({$token['regexp']})/";
if (!$isMatch && preg_match($regexp, $this->expression, $matches)) {
$isMatch = true;
$this->tokenObjs[] = $tokenObj = $this->tokenFactory($token, $matches[1]);
//echo "{$this->expression} -> {$tokenObj->type}: '{$tokenObj->value}'\n";
$this->expression = substr($this->expression, strlen($matches[1]));
break;
}
}
if (!$isMatch) {
throw new Exception("Unrecognized token: '{$this->expression}'");
}
}
}
public function registerObject($classSuffix, $type, $regexp)
{
$this->registeredTokens[$type] = array(
'regexp' => $regexp,
'type' => $type,
'classSuffix' => $classSuffix,
);
}
public function current()
{
return $this->tokenObjs[$this->iPointer];
}
public function key()
{
return $this->tokenObjs[$this->iPointer]->type;
}
public function next()
{
$this->iPointer++;
}
public function rewind()
{
$this->iPointer = 0;
}
public function valid()
{
return ($this->iPointer < sizeof($this->tokenObjs));
}
}
class Calc
{
private $expression;
private $stack;
private $rpnNotation;
private $tokenizer;
public function __construct($expr)
{
$this->expression = preg_replace('/\\s+/i', '$1', $expr);
$this->expression = strtr($this->expression, '{}[]', '()()');
if (empty($this->expression)) {
throw new Exception('Expression to evaluate is empty');
}
$this->stack = new Stack();
$this->rpnNotation = new Queue();
$this->tokenizer = new Tokenizer($this->expression);
$this->tokenizer->registerObject(null, 'number', '[\\d.]+');
$this->tokenizer->registerObject(null, 'l_bracket', '\(');
$this->tokenizer->registerObject(null, 'r_bracket', '\)');
$this->tokenizer->registerObject(null, 'coma', '\,');
$this->tokenizer->registerObject('operator', 'minus', '\-');
$this->tokenizer->registerObject('operator', 'plus', '\+');
$this->tokenizer->registerObject('operator', 'divide', '\/');
$this->tokenizer->registerObject('operator', 'multiply', '\*');
$this->tokenizer->registerObject('operator', 'power', '\^');
$this->tokenizer->registerObject('constant', 'pi', 'PI');
$this->tokenizer->registerObject('constant', 'e', 'E');
$this->tokenizer->registerObject('function', 'sin', 'sin');
$this->tokenizer->registerObject('function', 'cos', 'cos');
$this->tokenizer->registerObject('function', 'tg', 'tg');
$this->tokenizer->registerObject('function', 'ctg', 'ctg');
$this->tokenizer->registerObject('function', 'max', 'max');
//echo "Expression: {$this->expression}\n";
//echo "-----------------------------\n";
}
/**
* @link http://en.wikipedia.org/wiki/Shunting-yard_algorithm
* @link http://pl.wikipedia.org/wiki/Odwrotna_notacja_polska
*/
private function convertToRpn()
{
$this->tokenizer->tokenize();
//echo "Converting to postfix notation:\n\n";
foreach ($this->tokenizer as $token) {
// Jeśli symbol jest liczbą
if ($token instanceof Number) {
// dodaj go do kolejki wyjście
$this->rpnNotation->enqueue($token);
} // Jeśli symbol jest funkcją
elseif ($token instanceof Funct) {
// włóż go na stos.
$this->stack->push($token);
} // Jeśli symbol jest znakiem oddzielającym argumenty funkcji (np. przecinek):
elseif ($token instanceof Coma) {
// Dopóki najwyższy element stosu nie jest lewym nawiasem,
$leftBracketExists = false;
while (!($this->stack->top() instanceof L_bracket)) {
// zdejmij element ze stosu i dodaj go do kolejki wyjście.
$this->rpnNotation->enqueue($this->stack->pop());
}
// Jeśli lewy nawias nie został napotkany oznacza to,
// że znaki oddzielające zostały postawione w złym miejscu lub nawiasy są źle umieszczone.
if (!($this->stack->top() instanceof L_bracket)) {
throw new Exception('Missing left bracket in expression');
}
} // Jeśli symbol jest operatorem, o1
elseif ($token instanceof Operator) {
// 1) dopóki na górze stosu znajduje się operator, o2 taki, że:
if (!$this->stack->isEmpty() && ($stackTop = $this->stack->top()) && $stackTop instanceof Operator) {
// o1 jest łączny lub lewostronnie łączny i jego kolejność wykonywania jest mniejsza
// lub równa kolejności wyk. o2, lub
$test1 = (in_array($token->associativity(), array('both', 'left')))
&& ($token->priority() <= $stackTop->priority());
//o1 jest prawostronnie łączny i jego kolejność wykonywania jest mniejsza od o2,
$test2 = (in_array($token->associativity(), array('right')))
&& ($token->priority() < $stackTop->priority());
if ($test1 || $test2) {
// zdejmij o2 ze stosu i dołóż go do kolejki wyjściowej;
$this->rpnNotation->enqueue($this->stack->pop());
}
}
// 2) włóż o1 na stos operatorów.
$this->stack->push($token);
} // Jeśeli symbol jest lewym nawiasem
elseif ($token instanceof L_bracket) {
// to włóż go na stos.
$this->stack->push($token);
} // Jeśeli symbol jest prawym nawiasem
elseif ($token instanceof R_bracket) {
$leftBracketExists = false;
while ($operator = $this->stack->pop()) {
// dopóki symbol na górze stosu nie jest lewym nawiasem,
if ($operator instanceof L_bracket) {
$leftBracketExists = true;
break;
} // to zdejmuj operatory ze stosu i dokładaj je do kolejki wyjście
else {
$this->rpnNotation->enqueue($operator);
}
}
// Teraz, jeśli najwyższy element na stosie jest funkcją, także dołóż go do kolejki wyjście.
if ($this->stack->top() instanceof Funct) {
$this->rpnNotation->enqueue($this->stack->pop());
}
// Jeśli stos zostanie opróżniony i nie napotkasz lewego nawiasu, oznacza to,
// że nawiasy zostały źle umieszczone.
if ($this->stack->isEmpty() && !$leftBracketExists) {
throw new Exception('Missing left bracket in expression');
}
}
}
// Jeśli nie ma więcej symboli do przeczytania, zdejmuj wszystkie symbole ze stosu (jeśli jakieś są)
// i dodawaj je do kolejki wyjścia.
while (!$this->stack->isEmpty()) {
$operator = $this->stack->pop();
// Powinny to być wyłącznie operatory,
// jeśli natrafisz na jakiś nawias, znaczy to, że nawiasy zostały źle umieszczone.
if ($operator instanceof Bracket) {
throw new Exception('Mismatched brackets in expression');
}
$this->rpnNotation->enqueue($operator);
}
}
private function process()
{
//echo "Processing postfix notation:\n\n";
$tempStack = new Stack();
while ($token = $this->rpnNotation->dequeue()) {
if ($token instanceof Number) {
$tempStack->push($token);
} elseif (($token instanceof Operator) || ($token instanceof Funct)) {
/** @var $token Operator|Funct */
if ($tempStack->count() < $token->numOfArgs()) {
throw new Exception(
sprintf(
'Required %d arguments, %d given.',
$token->numOfArgs(),
$tempStack->count()
)
);
}
$arg = $tempStack->popMultiple($token->numOfArgs());
$tempStack->push($token->execute(array_reverse($arg)));
}
}
return $tempStack->pop()->value;
}
public function evaluate()
{
$this->convertToRpn();
return $this->process();
}
}
/**
* sin(PI/2+2*PI)+cos(2*2*PI)+tg(2*PI)+ctg(PI/2+2*PI)+2^2/2-2+2*2-4 + ((2+2)*2-(4/2*2)*2) =
* 1 + 1 + 0 + 0 + 0
*/
$ret = null;
try {
$calc = new Calc($_GET['expression']);
$ret = $calc->evaluate();
} catch (Exception $e) {
$ret = $e->getMessage();
}
echo json_encode(array('result' => $ret));