Advertisement
Guest User

Untitled

a guest
May 4th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * negBin to decimal
  5. * for tests
  6. */
  7. function toDec($subBin = []) {
  8. $res = 0;
  9. foreach ($subBin as $k => $val) {
  10. $res += $val * pow(-2, $k);
  11. }
  12.  
  13. return $res;
  14. }
  15.  
  16. /**
  17. * main solution
  18. * negBin addition
  19. */
  20. function solution($A, $B) {
  21. $len = max(count($A), count($B));
  22. $res = [];
  23.  
  24. for ($i=0; $i < $len + 2; $i++) {
  25. if (empty($res[$i])) $res[$i] = 0;
  26. if (empty($res[$i+1])) $res[$i+1] = 0;
  27. if (empty($res[$i+2])) $res[$i+2] = 0;
  28.  
  29. if (empty($A[$i])) $A[$i] = 0;
  30. if (empty($B[$i])) $B[$i] = 0;
  31.  
  32. $res[$i] += $A[$i] + $B[$i];
  33.  
  34. if ($res[$i] >= 2) {
  35. if ($res[$i + 1] && $res[$i] / $res[$i + 1] == 2) {
  36. $res[$i] = $res[$i + 1] = 0;
  37. } else {
  38. $res[$i + 1] += floor($res[$i] / 2);
  39. $res[$i + 2] += floor($res[$i] / 2);
  40. $res[$i] = $res[$i] % 2;
  41. }
  42. }
  43. }
  44.  
  45. $cnt = count($res);
  46. for ($c = $cnt - 1; $c >= 0; $c--) {
  47. if ($res[$c] == 0) {
  48. unset($res[$c]);
  49. } else {
  50. break;
  51. }
  52. }
  53.  
  54. $cnt = count($res);
  55. if($res[$cnt - 1] != 0 && $res[$cnt - 2]/$res[$cnt - 1] == 2) {
  56. array_pop($res);
  57. array_pop($res);
  58. }
  59.  
  60. return $res;
  61. }
  62.  
  63.  
  64. // tests
  65. $tests = [
  66. [
  67. 'n1' => [0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1],
  68. 'n2' => [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
  69. 'res' => [0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1]
  70. ],
  71. [
  72. 'n1' => [1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1],
  73. 'n2' => [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
  74. 'res' => [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1]
  75. ],
  76. [
  77. 'n1' => [0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1],
  78. 'n2' => [0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1],
  79. 'res' => [0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1]
  80. ],
  81. [
  82. 'n1' => [0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1],
  83. 'n2' => [0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
  84. 'res' => [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
  85. ],
  86. ];
  87.  
  88. foreach ($tests as $k => $test) {
  89. $res = solution($test['n1'], $test['n2']);
  90.  
  91. if ($res == $test['res']) {
  92. echo 'test case ' . $k . " - Passed!\n";
  93. } else {
  94. echo 'test case ' . $k . " - ERROR!\n";
  95. }
  96.  
  97. echo toDec($test['n1']) . ' + ' . toDec($test['n2']) . ' (Expected:' . toDec($res) . ")\n" .
  98. 'solution result: ' . implode('', $res) . "\n" .
  99. 'test result: ' . implode('', $test['res']) . "\n\n";
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement