Skip to content

Instantly share code, notes, and snippets.

@alfaproject
Created July 1, 2012 16:18
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 alfaproject/3028848 to your computer and use it in GitHub Desktop.
Save alfaproject/3028848 to your computer and use it in GitHub Desktop.
Sapo F25 Challenge
<?php
/**
* quick f15 prototype that should do what's needed
* no item indexes to make it harder
* `$items[$i] = 'item '. $i` would be too easy and even smaller
*/
function f15($page)
{
$first = ($page - 1) * 15 + 1;
for ($i = $first; $i < $first + 15; $i++)
{
$items[] = 'item ' . $i;
}
return $items;
}
/**
* try at the f25 challenge
*/
function f25_big($page)
{
// calculate the first page needed from f15
$f15_page = $page + floor(2 * ($page - 1) / 3);
// fetch 3 pages of items from f15 (sometimes we only need 2, but small code is the target)
$f15_items = array_merge(f15($f15_page), f15($f15_page + 1), f15($f15_page + 2));
// calculate the offset from the first page of items we got
$f15_page_offset = 25 * ($page - 1) - 15 * ($f15_page - 1);
// return the 25 items after this offset
return array_splice($f15_items, $f15_page_offset, 25);
}
/**
* f25 after shortening variables and math simplifications: 119 chars
*/
function f25($p){$f=floor((5*$p-2)/3);return array_splice(array_merge(f15($f),f15($f+1),f15($f+2)),25*$p-15*$f-10,25);}
// poor man's unit test
for ($i = 1; $i <= 10000; $i++)
{
$items = f25($i);
if ($items[0] != 'item ' . (($i - 1) * 25 + 1) || $items[24] != 'item ' . ($i * 25))
{
echo "Page ". $i . " » " . $items[0] . " to " . $items[24] . " » failed\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment