Skip to content

Instantly share code, notes, and snippets.

@SamuelMwangiW
Last active March 26, 2021 20:26
Show Gist options
  • Select an option

  • Save SamuelMwangiW/08766621e1ef7c35bd33be6d490865d7 to your computer and use it in GitHub Desktop.

Select an option

Save SamuelMwangiW/08766621e1ef7c35bd33be6d490865d7 to your computer and use it in GitHub Desktop.
An over engineered solution to (https://www.interviewcake.com/question/python/inflight-entertainment) writen in PHP
<?php
class InflightEntertainment
{
private int $flightLength;
private array $movieDuration;
private array $matchedMovies = [];
public function __construct(int $lengthOfFlight, array $movieDuration)
{
$this->flightLength = $lengthOfFlight;
$this->movieDuration = $movieDuration;
$this->analyse();
}
public function moviesAvailable(): bool
{
return count($this->matchedMovies) > 0;
}
public function getMatchedMovies(): array
{
return array_values($this->matchedMovies);
}
private function analyse()
{
if (!$this->moviesEmpty()) {
$this->computeValidChoices();
}
return $this;
}
private function moviesEmpty(): bool
{
return count($this->movieDuration) === 0 || empty($this->movieDuration);
}
private function computeValidChoices()
{
foreach ($this->movieDuration as $index => $trialDuration) {
//Am assuming we can't watch the same movie twice.
// I could have used array_splice but that would reset the indexes which would make the code longer
$otherMovies = $this->movieDuration;
unset($otherMovies[$index]);
foreach ($otherMovies as $index2 => $duration) {
if ($this->flightLength === $this->sum($duration, $trialDuration)) {
$this->addMatchedMovie($index, $index2);
}
}
}
return $this;
}
private function addMatchedMovie(int $index, int $index2)
{
$key = $index < $index2 ? "{$index}{$index2}" : "{$index2}{$index}";
$this->matchedMovies[$key] = [$this->movieDuration[$index], $this->movieDuration[$index2]]; //avoid duplicates
return $this;
}
private function sum(int $value1 = 0, int $value2 = 0): int
{
return $value1 + $value2;
}
}
$movieDuration = [1, 2, 3, 4, 5, 6, 2, 3, 4, 2, 1, 5, 4, 3];
$lengthOfFlight = 6;
$obj = new InflightEntertainment($lengthOfFlight, $movieDuration);
if ($obj->moviesAvailable()) {
echo "I found movies that match your flight." . PHP_EOL;
print_r($obj->getMatchedMovies());
} else {
echo "No movies match your flight.";
}
@SamuelMwangiW
Copy link
Author

SamuelMwangiW commented Mar 26, 2021

While inefficient to have nested loops making the solution O(n^2) as opposed to the sweet spot O(n), there is a real chance for 2 or more movies to share exact watch times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment