Skip to content

Commit

Permalink
Common Denominators
Browse files Browse the repository at this point in the history
  • Loading branch information
nick322 committed Feb 17, 2020
1 parent d069f23 commit 350c310
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 5-kyu/Common Denominators/src/convertFrac.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
function convertFrac($lst)
{
$gcd_item = [];
foreach ($lst as $v) {
// if(isset($v[1]))
// $gcd_item[] = $v[1];
if (gcd($v[0], $v[1]) == 1) {
$gcd_item[] = $v[1];
} else {
$gcd_item[] = $v[1] / gcd($v[0], $v[1]);
}
}
if (count($gcd_item) > 0) {
$lcm = findlcm($gcd_item, count($gcd_item));
}
// var_dump($lst, $gcd_item, '$lcm = ' . $lcm);
// var_dump($lcm);

$result = '';

foreach ($lst as $v) {
$result = $result . '(' . (($lcm / $v[1]) * $v[0]) . ',' . ($lcm) . ')';
}
return $result;
}

function gcd($a, $b)
{
return ($a % $b) ? gcd($b, $a % $b) : $b;
}
// https://www.geeksforgeeks.org/lcm-of-given-array-elements/
// Returns LCM of array elements
function findlcm($arr, $n)
{

// Initialize result
$ans = $arr[0];

// ans contains LCM of
// arr[0], ..arr[i]
// after i'th iteration,
for ($i = 1; $i < $n; $i++)
$ans = ((($arr[$i] * $ans)) / (gcd($arr[$i], $ans)));

return $ans;
}
22 changes: 22 additions & 0 deletions 5-kyu/Common Denominators/test/CommonDenominatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use PHPUnit\Framework\TestCase;

class CommonDenominatorTest extends TestCase
{
private function revTest($actual, $expected)
{
$this->assertEquals($expected, $actual);
}
public function testBasics()
{
$lst = [[1, 2], [1, 3], [1, 4]];
$this->revTest(convertFrac($lst), "(6,12)(4,12)(3,12)");
$lst = [[69, 130], [87, 1310], [3, 4]];
$this->revTest(convertFrac($lst), "(18078,34060)(2262,34060)(25545,34060)");
$lst = [];
$this->revTest(convertFrac($lst), "");
$lst = [[77, 130], [84, 131], [3, 4]];
$this->revTest(convertFrac($lst), "(20174,34060)(21840,34060)(25545,34060)");
}
}
4 changes: 4 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,9 @@
<file>7-kyu/Exes and Ohs/src/XO.php</file>
<directory>7-kyu/Exes and Ohs/test</directory>
</testsuite>
<testsuite name="5-kyu-Common-Denominators">
<file>5-kyu/Common Denominators/src/convertFrac.php</file>
<directory>5-kyu/Common Denominators/test</directory>
</testsuite>
</testsuites>
</phpunit>

0 comments on commit 350c310

Please sign in to comment.