Created
April 13, 2022 08:39
-
-
Save moh6mmad/79d3c5ea24e7347c84b774a8b407f8e1 to your computer and use it in GitHub Desktop.
Solution to return filenames
This file contains 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 | |
/** | |
* Solution to return image names | |
* | |
* @param string $S | |
* | |
* @return string | |
*/ | |
function solution($S) | |
{ | |
$rawPhotos = explode("\n", $S); | |
$locations = $finalNames = $photos = $locationArray = []; | |
foreach ($rawPhotos as $index => $rawPhoto) { | |
list($filename, $location, $datetime) = explode(",", $rawPhoto); | |
if (empty($locations[trim($location)][$filename])) { | |
$locations[trim($location)][$filename] = 0; | |
} | |
$locations[trim($location)][$filename] = count($locations[trim($location)]); | |
$locationArray[trim($location)] = empty($locationArray[trim($location)]) ? 1 : $locationArray[trim($location)]+1; | |
$photos[] = [ | |
'index' => $index, | |
'filename' => $filename, | |
'date' => trim($datetime), | |
'location' => trim($location) | |
]; | |
} | |
usort($photos, function ($a, $b) { | |
return strtotime($a['date']) - strtotime($b['date']); | |
}); | |
foreach ($photos as $index => $photo) { | |
$strPad = strlen((string)($locationArray[$photo['location']])); | |
$number = str_pad($locations[$photo['location']][$photo['filename']], $strPad, '0', STR_PAD_LEFT); | |
$finalNames[$photo['index']] = $photo['location'] . $number . '.'. pathinfo($photo['filename'], PATHINFO_EXTENSION); | |
} | |
return implode("\n", $finalNames); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment