Skip to content

Instantly share code, notes, and snippets.

@moh6mmad
Created April 13, 2022 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moh6mmad/79d3c5ea24e7347c84b774a8b407f8e1 to your computer and use it in GitHub Desktop.
Save moh6mmad/79d3c5ea24e7347c84b774a8b407f8e1 to your computer and use it in GitHub Desktop.
Solution to return filenames
<?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