Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created June 20, 2013 13:25
Show Gist options
  • Select an option

  • Save ackintosh/5822647 to your computer and use it in GitHub Desktop.

Select an option

Save ackintosh/5822647 to your computer and use it in GitHub Desktop.
<?php
class Ball
{
public $dataSets = array();
public function run($input)
{
$this->set($input);
$results = array();
foreach ($this->dataSets as $d) {
$results[] = $this->parse(explode(' ', $d));
}
return implode("\n", $results);
}
public function set($input)
{
$splited = preg_split('/[\r\n|\r|\n]/', $input);
for ($i = 0; $i < count($splited); $i++) {
if ($i === 0) continue;
$this->dataSets[] = $splited[$i];
}
}
public function parse(Array $data, $b = null, $c = null)
{
if ($b === null && $c === null) list($b, $c) = array(new AckArray(), new AckArray());
if (empty($data)) return 'YES';
$input_num = array_shift($data);
if ($b->last() >= $input_num and $c->last() >= $input_num) return 'NO';
if ($b->last() >= $input_num) {
$c->add($input_num);
return $this->parse($data, $b, $c);
}
if ($c->last() >= $input_num) {
$b->add($input_num);
return $this->parse($data, $b, $c);
}
($b->last() > $c->last()) ? $b->add($input_num) : $c->add($input_num);
return $this->parse($data, $b, $c);
}
}
class AckArray extends ArrayObject
{
public function first()
{
if ($this->count() === 0) return null;
return $this->offsetGet(0);
}
public function last()
{
if ($this->count() === 0) return null;
return $this->offsetGet($this->last_index());
}
public function add($value)
{
$this->offsetSet($this->last_index() + 1, $value);
}
public function last_index()
{
return $this->count() - 1;
}
}
<?php
require_once 'Ball.php';
class BallTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->ball = new Ball();
$this->input = <<< __EOS__
2
3 1 4 2 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
__EOS__;
}
/**
* @test
*/
public function should_have_two_dataSet()
{
$this->ball->run($this->input);
$this->assertEquals(2, count($this->ball->dataSets));
}
/**
* @test
*/
public function parse_should_return_YES_if_input_is_valid()
{
$input = '3 1 4 2 5 6 7 8 9 10';
$expect = 'YES';
$this->assertEquals($expect, $this->ball->parse(explode(' ', $input)));
}
/**
* @test
*/
public function parse_should_return_NO_if_input_is_invalid()
{
$input = '10 9 8 7 6 5 4 3 2 1';
$expect = 'NO';
$this->assertEquals($expect, $this->ball->parse(explode(' ', $input)));
}
/**
* @test
*/
public function run_should_return_result_rows()
{
$expect = <<< __EOS__
YES
NO
__EOS__;
$this->assertEquals($expect, $this->ball->run($this->input));
}
}
<?php
$ball = new Ball();
$input = <<< __EOS__
2
3 1 4 2 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
__EOS__;
echo $ball->run($input);
/*
YES
NO
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment