Created
December 2, 2024 07:12
-
-
Save LukeTowers/d35830a66fdaf85e23f05c7385285dcb to your computer and use it in GitHub Desktop.
AOC-2024
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function csvToArray($csvString, $delimiter = ",", $lineBreak = "\n") | |
{ | |
$csvArray = []; | |
$rows = str_getcsv($csvString, $lineBreak); // Parses the rows. Treats the rows as a CSV with \n as a delimiter | |
foreach ($rows as $row) { | |
$csvArray[] = str_getcsv($row, $delimiter); // Parses individual rows. Now treats a row as a regular CSV with ',' as a delimiter | |
} | |
return $csvArray; | |
} | |
$left = []; | |
$right = []; | |
$input = <<<INPUT | |
3 4 | |
4 3 | |
2 5 | |
1 3 | |
3 9 | |
3 3 | |
INPUT; | |
$input = str_replace(subject: $input, search: " ", replace: ","); | |
// dd($input); | |
$rows = csvToArray($input); | |
$left = array_column($rows, 0); | |
$right = array_column($rows, 1); | |
function getDistance($left, $right) | |
{ | |
sort($left); | |
sort($right); | |
$distance = 0; | |
foreach ($left as $i => $v) { | |
$distance += abs($left[$i] - $right[$i]); | |
} | |
} | |
function getSimilarity($left, $right) | |
{ | |
$return = 0; | |
$rightCount = []; | |
foreach ($right as $num) { | |
if (!isset($rightCount[$num])) { | |
$rightCount[$num] = 0; | |
} | |
$rightCount[$num]++; | |
} | |
foreach ($left as $num) { | |
$return += $num * ($rightCount[$num] ?? 0); | |
} | |
return $return; | |
} | |
return getSimilarity($left, $right); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment