Skip to content

Instantly share code, notes, and snippets.

@ReeSilva
Created February 1, 2016 21:59
Show Gist options
  • Save ReeSilva/c5564c971e10ca47a4da to your computer and use it in GitHub Desktop.
Save ReeSilva/c5564c971e10ca47a4da to your computer and use it in GitHub Desktop.
exercicio
<?php
namespace Creative;
class Exercise2
{
const MAX_ITERATIONS = 50;
private $adjacentChanges = 0;
private $iterations = 0;
private $whichHeighest = 1;
private $actualHighestKey = 0;
public function calculateHighestNumber(array $numbersArray, $switchesAllowed = 5)
{
while ($this->adjacentChanges < $switchesAllowed) {
$highest = $this->returnHighestValue($numbersArray, $this->whichHeighest);
if ($this->valueCanGoFirst($highest, $switchesAllowed)) {
$newArray = $this->changePosition($numbersArray, $highest);
$this->whichHeighest++;
$this->actualHighestKey++;
} else {
$this->whichHeighest++;
continue;
}
if ($this->iterations > self::MAX_ITERATIONS) {
break;
}
$this->iterations++;
}
return $newArray;
}
private function changePosition($array, $highestArray) {
for ($i = $highestArray["highest-key"]; $i > $this->actualHighestKey; $i--) {
$secondNumber = $array[$i];
$array[$i] = $array[$i-1];
$array[$i-1] = $secondNumber;
$this->adjacentChanges++;
}
return $array;
}
private function returnHighestValue($array, $whichHighest) {
$bkpArray = $array;
sort($array);
$reversedArray = array_reverse($array);
$highestKey = array_keys($bkpArray, $reversedArray[$whichHighest - 1]);
$highestValue = $bkpArray[$highestKey[0]];
return array(
"highest-key" => $highestKey[0],
"highest-value" => $highestValue
);
}
private function valueCanGoFirst($highestArray, $switchesAllowed) {
if (($highestArray["highest-key"] - $this->actualHighestKey) <= ($switchesAllowed - $this->adjacentChanges)) {
return TRUE;
}
return FALSE;
}
}
$exercise= new \Creative\Exercise2;
$result = $exercise->calculateHighestNumber(array(2,5,7,1,8));
print_r($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment