initial php exercises

This commit is contained in:
Ben Harris 2021-11-09 01:16:46 -05:00
parent aeb5e3d1fc
commit b751a92b9f
36 changed files with 1367 additions and 0 deletions

View File

@ -0,0 +1,25 @@
{
"blurb": "Given a moment, determine the moment that would be after a gigasecond has passed.",
"authors": [],
"contributors": [
"arueckauer",
"dkinzer",
"Dog",
"kunicmarko20",
"kytrinyx",
"lafent",
"MatheusNaldi",
"petemcfarlane",
"peteraba",
"TFarla",
"tstirrat15",
"zembrowski"
],
"files": {
"solution": ["Gigasecond.php"],
"test": ["GigasecondTest.php"],
"example": [".meta/example.php"]
},
"source": "Chapter 9 in Chris Pine's online Learn to Program tutorial.",
"source_url": "http://pine.fm/LearnToProgram/?Chapter=09"
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"gigasecond","id":"1e4be273a7654ea5be1a99717041875f","url":"https://exercism.org/tracks/php/exercises/gigasecond","handle":"benharri","is_requester":true,"auto_approve":false}

View File

@ -0,0 +1,30 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
function from(DateTimeImmutable $date): DateTimeImmutable
{
return $date->add(new DateInterval('PT1000000000S'));
}

View File

@ -0,0 +1,84 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class GigasecondTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass(): void
{
require_once 'Gigasecond.php';
}
public function dateSetup($date): DateTimeImmutable
{
$UTC = new DateTimeZone('UTC');
return new DateTimeImmutable($date, $UTC);
}
public function inputAndExpectedDates(): array
{
return [
['2011-04-25', '2043-01-01 01:46:40'],
['1977-06-13', '2009-02-19 01:46:40'],
['1959-07-19', '1991-03-27 01:46:40'],
['2015-01-24 22:00:00', '2046-10-02 23:46:40'],
['2015-01-24 23:59:59', '2046-10-03 01:46:39'],
];
}
public function inputDates(): array
{
return [
['2011-04-25'],
['1977-06-13'],
['1959-07-19'],
['2015-01-24 22:00:00'],
['2015-01-24 23:59:59'],
];
}
/**
* @dataProvider inputAndExpectedDates
* @param string $inputDate
* @param string $expected
*/
public function testFrom(string $inputDate, string $expected): void
{
$date = $this->dateSetup($inputDate);
$gs = from($date);
$this->assertSame($expected, $gs->format('Y-m-d H:i:s'));
}
/**
* @dataProvider inputDates
* @param string $inputDate
*/
public function testFromReturnType(string $inputDate): void
{
$date = $this->dateSetup($inputDate);
$this->assertInstanceOf(DateTimeImmutable::class, from($date));
}
}

51
php/gigasecond/HELP.md Normal file
View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit Gigasecond.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

32
php/gigasecond/README.md Normal file
View File

@ -0,0 +1,32 @@
# Gigasecond
Welcome to Gigasecond on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Given a moment, determine the moment that would be after a gigasecond
has passed.
A gigasecond is 10^9 (1,000,000,000) seconds.
## Source
### Contributed to by
- @arueckauer
- @dkinzer
- @Dog
- @kunicmarko20
- @kytrinyx
- @lafent
- @MatheusNaldi
- @petemcfarlane
- @peteraba
- @TFarla
- @tstirrat15
- @zembrowski
### Based on
Chapter 9 in Chris Pine's online Learn to Program tutorial. - http://pine.fm/LearnToProgram/?Chapter=09

View File

@ -0,0 +1,23 @@
{
"blurb": "Calculate the Hamming difference between two DNA strands.",
"authors": [],
"contributors": [
"arueckauer",
"dkinzer",
"Dog",
"kip-13",
"kunicmarko20",
"kytrinyx",
"lafent",
"marvinrabe",
"petemcfarlane",
"rossbearman"
],
"files": {
"solution": ["Hamming.php"],
"test": ["HammingTest.php"],
"example": [".meta/example.php"]
},
"source": "The Calculating Point Mutations problem at Rosalind",
"source_url": "http://rosalind.info/problems/hamm/"
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"hamming","id":"6eb639df9aa24411b50e19f7e8317d2f","url":"https://exercism.org/tracks/php/exercises/hamming","handle":"benharri","is_requester":true,"auto_approve":false}

51
php/hamming/HELP.md Normal file
View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit Hamming.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

37
php/hamming/Hamming.php Normal file
View File

@ -0,0 +1,37 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
function distance(string $strandA, string $strandB): int
{
if (strlen($strandA) != strlen($strandB))
throw new InvalidArgumentException('DNA strands must be of equal length.');
$distance = 0;
for ($i = 0; $i < strlen($strandA); $i++)
if ($strandA[$i] != $strandB[$i]) $distance++;
return $distance;
}

View File

@ -0,0 +1,75 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class HammingTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass(): void
{
require_once 'Hamming.php';
}
public function testNoDifferenceBetweenIdenticalStrands(): void
{
$this->assertEquals(0, distance('A', 'A'));
}
public function testCompleteHammingDistanceOfForSingleNucleotideStrand(): void
{
$this->assertEquals(1, distance('A', 'G'));
}
public function testCompleteHammingDistanceForSmallStrand(): void
{
$this->assertEquals(2, distance('AG', 'CT'));
}
public function testSmallHammingDistance(): void
{
$this->assertEquals(1, distance('AT', 'CT'));
}
public function testSmallHammingDistanceInLongerStrand(): void
{
$this->assertEquals(1, distance('GGACG', 'GGTCG'));
}
public function testLargeHammingDistance(): void
{
$this->assertEquals(4, distance('GATACA', 'GCATAA'));
}
public function testHammingDistanceInVeryLongStrand(): void
{
$this->assertEquals(9, distance('GGACGGATTCTG', 'AGGACGGATTCT'));
}
public function testExceptionThrownWhenStrandsAreDifferentLength(): void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('DNA strands must be of equal length.');
distance('GGACG', 'AGGACGTGG');
}
}

46
php/hamming/README.md Normal file
View File

@ -0,0 +1,46 @@
# Hamming
Welcome to Hamming on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Calculate the Hamming Distance between two DNA strands.
Your body is made up of cells that contain DNA. Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells. In fact, the average human body experiences about 10 quadrillion cell divisions in a lifetime!
When cells divide, their DNA replicates too. Sometimes during this process mistakes happen and single pieces of DNA get encoded with the incorrect information. If we compare two strands of DNA and count the differences between them we can see how many mistakes occurred. This is known as the "Hamming Distance".
We read DNA using the letters C,A,G and T. Two strands might look like this:
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^ ^ ^ ^^
They have 7 differences, and therefore the Hamming Distance is 7.
The Hamming Distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :)
The Hamming distance is only defined for sequences of equal length, so
an attempt to calculate it between sequences of different lengths should
not work. The general handling of this situation (e.g., raising an
exception vs returning a special value) may differ between languages.
## Source
### Contributed to by
- @arueckauer
- @dkinzer
- @Dog
- @kip-13
- @kunicmarko20
- @kytrinyx
- @lafent
- @marvinrabe
- @petemcfarlane
- @rossbearman
### Based on
The Calculating Point Mutations problem at Rosalind - http://rosalind.info/problems/hamm/

View File

@ -0,0 +1,12 @@
{
"blurb": "The classical introductory exercise. Just say \"Hello, World!\"",
"authors": ["duffn"],
"contributors": ["arueckauer", "joseph-walker", "kytrinyx", "petemcfarlane"],
"files": {
"solution": ["HelloWorld.php"],
"test": ["HelloWorldTest.php"],
"example": [".meta/example.php"]
},
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "http://en.wikipedia.org/wiki/%22Hello,_world!%22_program"
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"hello-world","id":"8a95fe11145e47068e6e33734b844fe4","url":"https://exercism.org/tracks/php/exercises/hello-world","handle":"benharri","is_requester":true,"auto_approve":false}

51
php/hello-world/HELP.md Normal file
View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit HelloWorld.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

View File

@ -0,0 +1,6 @@
<?php
function helloWorld()
{
return "Hello, World!";
}

View File

@ -0,0 +1,38 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class HelloWorldTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass(): void
{
require_once 'HelloWorld.php';
}
public function testHelloWorld(): void
{
$this->assertEquals('Hello, World!', helloWorld());
}
}

37
php/hello-world/README.md Normal file
View File

@ -0,0 +1,37 @@
# Hello World
Welcome to Hello World on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise. Just say "Hello, World!".
["Hello, World!"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is
the traditional first program for beginning programming in a new language
or environment.
The objectives are simple:
- Write a function that returns the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
## Source
### Created by
- @duffn
### Contributed to by
- @arueckauer
- @joseph-walker
- @kytrinyx
- @petemcfarlane
### Based on
This is an exercise to introduce users to using Exercism - http://en.wikipedia.org/wiki/%22Hello,_world!%22_program

View File

@ -0,0 +1,12 @@
{
"blurb": "Determine if a word or phrase is an isogram.",
"authors": ["ecrmnn"],
"contributors": ["arueckauer", "kunicmarko20", "kytrinyx", "petemcfarlane"],
"files": {
"solution": ["Isogram.php"],
"test": ["IsogramTest.php"],
"example": [".meta/example.php"]
},
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Isogram"
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"isogram","id":"29d2de5920bc4f26b033aa93159e85c0","url":"https://exercism.org/tracks/php/exercises/isogram","handle":"benharri","is_requester":true,"auto_approve":false}

51
php/isogram/HELP.md Normal file
View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit Isogram.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

31
php/isogram/Isogram.php Normal file
View File

@ -0,0 +1,31 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
function isIsogram(string $word): bool
{
$w = str_replace(' ', '', str_replace('-', '', mb_strtolower($word)));
return count(array_unique(mb_str_split($w))) == mb_strlen($w);
}

View File

@ -0,0 +1,83 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class IsogramTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass(): void
{
require_once 'Isogram.php';
}
public function testIsogram(): void
{
$this->assertTrue(isIsogram('duplicates'));
}
public function testNotIsogram(): void
{
$this->assertFalse(isIsogram('eleven'));
}
public function testMediumLongIsogram(): void
{
$this->assertTrue(isIsogram('subdermatoglyphic'));
}
public function testCaseInsensitive(): void
{
$this->assertFalse(isIsogram('Alphabet'));
}
public function testIsogramWithHyphen(): void
{
$this->assertTrue(isIsogram('thumbscrew-japingly'));
}
public function testIgnoresMultipleHyphens(): void
{
$this->assertTrue(isIsogram('Hjelmqvist-Gryb-Zock-Pfund-Wax'));
}
public function testWorksWithGermanLetters(): void
{
$this->assertTrue(isIsogram('Heizölrückstoßabdämpfung'));
}
public function testIgnoresSpaces(): void
{
$this->assertFalse(isIsogram('the quick brown fox'));
}
public function testIgnoresSpaces2(): void
{
$this->assertTrue(isIsogram('Emily Jung Schwartzkopf'));
}
public function testDuplicateAccentedLetters(): void
{
$this->assertFalse(isIsogram('éléphant'));
}
}

36
php/isogram/README.md Normal file
View File

@ -0,0 +1,36 @@
# Isogram
Welcome to Isogram on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
- lumberjacks
- background
- downstream
- six-year-old
The word *isograms*, however, is not an isogram, because the s repeats.
## Source
### Created by
- @ecrmnn
### Contributed to by
- @arueckauer
- @kunicmarko20
- @kytrinyx
- @petemcfarlane
### Based on
Wikipedia - https://en.wikipedia.org/wiki/Isogram

View File

@ -0,0 +1,10 @@
{
"blurb": "Reverse a string",
"authors": ["MichaelBunker"],
"contributors": [],
"files": {
"solution": ["ReverseString.php"],
"test": ["ReverseStringTest.php"],
"example": [".meta/example.php"]
}
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"reverse-string","id":"e9972cdd22b24a2eaf5a70dfd91c9a7d","url":"https://exercism.org/tracks/php/exercises/reverse-string","handle":"benharri","is_requester":true,"auto_approve":false}

View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit ReverseString.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

View File

@ -0,0 +1,18 @@
# Reverse String
Welcome to Reverse String on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Reverse a string
For example:
input: "cool"
output: "looc"
## Source
### Created by
- @MichaelBunker

View File

@ -0,0 +1,30 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
function reverseString(string $text): string
{
return strrev($text);
}

View File

@ -0,0 +1,63 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class ReverseStringTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass(): void
{
require_once 'ReverseString.php';
}
public function testEmptyString(): void
{
$this->assertEquals("", reverseString(""));
}
public function testWord(): void
{
$this->assertEquals("tobor", reverseString("robot"));
}
public function testCapitalizedWord(): void
{
$this->assertEquals("nemaR", reverseString("Ramen"));
}
public function testSentenceWithPunctuation(): void
{
$this->assertEquals("!yrgnuh m'I", reverseString("I'm hungry!"));
}
public function testPalindrome(): void
{
$this->assertEquals("racecar", reverseString("racecar"));
}
public function testEvenSizedWord(): void
{
$this->assertEquals("reward", reverseString("drawer"));
}
}

View File

@ -0,0 +1,10 @@
{
"blurb": "Tally the results of a small football competition.",
"authors": ["MichaelBunker"],
"contributors": ["dstockto"],
"files": {
"solution": ["Tournament.php"],
"test": ["TournamentTest.php"],
"example": [".meta/example.php"]
}
}

View File

@ -0,0 +1 @@
{"track":"php","exercise":"tournament","id":"9d98390b5a7547a8bf4d75f9d2551a75","url":"https://exercism.org/tracks/php/exercises/tournament","handle":"benharri","is_requester":true,"auto_approve":false}

51
php/tournament/HELP.md Normal file
View File

@ -0,0 +1,51 @@
# Help
## Running the tests
## Running the tests
1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`.
To find the Exercism workspace run
➜ exercism debug | grep Workspace
1. Get [PHPUnit] if you don't have it already.
➜ wget -O phpunit https://phar.phpunit.de/phpunit-9.phar
➜ chmod +x phpunit
➜ ./phpunit --version
2. Execute the tests:
➜ ./phpunit file_to_test.php
For example, to run the tests for the Hello World exercise, you would run:
➜ ./phpunit HelloWorldTest.php
[PHPUnit]: http://phpunit.de
## Submitting your solution
You can submit your solution using the `exercism submit Tournament.php` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [PHP track's documentation](https://exercism.org/docs/tracks/php)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [/r/php](https://www.reddit.com/r/php) is the PHP subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/php) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

78
php/tournament/README.md Normal file
View File

@ -0,0 +1,78 @@
# Tournament
Welcome to Tournament on Exercism's PHP Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Tally the results of a small football competition.
Based on an input file containing which team played against which and what the
outcome was, create a file with a table like this:
```text
Team | MP | W | D | L | P
Devastating Donkeys | 3 | 2 | 1 | 0 | 7
Allegoric Alaskans | 3 | 2 | 0 | 1 | 6
Blithering Badgers | 3 | 1 | 0 | 2 | 3
Courageous Californians | 3 | 0 | 1 | 2 | 1
```
What do those abbreviations mean?
- MP: Matches Played
- W: Matches Won
- D: Matches Drawn (Tied)
- L: Matches Lost
- P: Points
A win earns a team 3 points. A draw earns 1. A loss earns 0.
The outcome should be ordered by points, descending. In case of a tie, teams are ordered alphabetically.
## Input
Your tallying program will receive input that looks like:
```text
Allegoric Alaskans;Blithering Badgers;win
Devastating Donkeys;Courageous Californians;draw
Devastating Donkeys;Allegoric Alaskans;win
Courageous Californians;Blithering Badgers;loss
Blithering Badgers;Devastating Donkeys;loss
Allegoric Alaskans;Courageous Californians;win
```
The result of the match refers to the first team listed. So this line:
```text
Allegoric Alaskans;Blithering Badgers;win
```
means that the Allegoric Alaskans beat the Blithering Badgers.
This line:
```text
Courageous Californians;Blithering Badgers;loss
```
means that the Blithering Badgers beat the Courageous Californians.
And this line:
```text
Devastating Donkeys;Courageous Californians;draw
```
means that the Devastating Donkeys and Courageous Californians tied.
## Source
### Created by
- @MichaelBunker
### Contributed to by
- @dstockto

View File

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
class Tournament
{
public function __construct()
{
$this->teams = [];
}
public function tally(string $scores) : string
{
foreach (explode(PHP_EOL, $scores) as $game)
{
[$t1, $t2, $outcome] = explode(';', $game);
if (count($split) < 3) continue;
$team1 = $this->teams[$t1] ?? ["Team" => $t1, "MP" => 0, "P" => 0, "W" => 0, "L" => 0, "D" => 0];
$team2 = $this->teams[$t2] ?? ["Team" => $t2, "MP" => 0, "P" => 0, "W" => 0, "L" => 0, "D" => 0];
$team1["MP"]++;
$team2["MP"]++;
switch ($outcome)
{
case "win":
$team1["P"] += 3;
$team1["W"]++;
$team2["L"]++;
break;
case "loss":
$team2["P"] += 3;
$team2["W"]++;
$team1["L"]++;
break;
case "draw":
$team1["P"]++;
$team2["P"]++;
$team1["D"]++;
$team2["D"]++;
break;
}
$this->teams[$t1] = $team1;
$this->teams[$t2] = $team2;
}
array_multisort(array_column($this->teams, 'P'), SORT_DESC,
array_column($this->teams, 'Team', SORT_ASC),
$this->teams);
$result[] = "Team | MP | W | D | L | P";
foreach ($this->teams as $t)
{
$result[] = sprintf("%-30s | %2d | %2d | %2d | %2d | %2d",
$t["Team"], $t["MP"], $t["W"], $t["D"], $t["L"], $t["P"]);
}
return implode(PHP_EOL, $result);
}
}

View File

@ -0,0 +1,177 @@
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class TournamentTest extends PHPUnit\Framework\TestCase
{
private Tournament $tournament;
public static function setUpBeforeClass(): void
{
require_once 'Tournament.php';
}
protected function setUp(): void
{
$this->tournament = new Tournament();
}
public function testHeaderOnlyNoTeams(): void
{
$scores = '';
$expected = 'Team | MP | W | D | L | P';
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testWinIsThreePointsLossIsZeroPoints(): void
{
$scores = 'Allegoric Alaskans;Blithering Badgers;win';
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" .
"Blithering Badgers | 1 | 0 | 0 | 1 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testWinCanAlsoBeExpressedAsALoss(): void
{
$scores = 'Blithering Badgers;Allegoric Alaskans;loss';
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" .
"Blithering Badgers | 1 | 0 | 0 | 1 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testDifferentTeamsCanWin(): void
{
$scores = 'Blithering Badgers;Allegoric Alaskans;win';
$expected =
"Team | MP | W | D | L | P\n" .
"Blithering Badgers | 1 | 1 | 0 | 0 | 3\n" .
"Allegoric Alaskans | 1 | 0 | 0 | 1 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testADrawIsOnePointEach(): void
{
$scores = 'Allegoric Alaskans;Blithering Badgers;draw';
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 1 | 0 | 1 | 0 | 1\n" .
"Blithering Badgers | 1 | 0 | 1 | 0 | 1";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testThereCanBeMultipleMatches(): void
{
$scores =
"Allegoric Alaskans;Blithering Badgers;win\n" .
"Allegoric Alaskans;Blithering Badgers;win";
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" .
"Blithering Badgers | 2 | 0 | 0 | 2 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testThereCanBeMoreThanOneWinner(): void
{
$scores =
"Allegoric Alaskans;Blithering Badgers;loss\n" .
"Allegoric Alaskans;Blithering Badgers;win";
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 2 | 1 | 0 | 1 | 3\n" .
"Blithering Badgers | 2 | 1 | 0 | 1 | 3";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testThereCanBeMoreThanTwoTeams(): void
{
$scores =
"Allegoric Alaskans;Blithering Badgers;win\n" .
"Blithering Badgers;Courageous Californians;win\n" .
"Courageous Californians;Allegoric Alaskans;loss";
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" .
"Blithering Badgers | 2 | 1 | 0 | 1 | 3\n" .
"Courageous Californians | 2 | 0 | 0 | 2 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testStandardInput(): void
{
$scores =
"Allegoric Alaskans;Blithering Badgers;win\n" .
"Devastating Donkeys;Courageous Californians;draw\n" .
"Devastating Donkeys;Allegoric Alaskans;win\n" .
"Courageous Californians;Blithering Badgers;loss\n" .
"Blithering Badgers;Devastating Donkeys;loss\n" .
"Allegoric Alaskans;Courageous Californians;win";
$expected =
"Team | MP | W | D | L | P\n" .
"Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" .
"Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" .
"Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" .
"Courageous Californians | 3 | 0 | 1 | 2 | 1";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testIncompleteCompetitionWhereNotAllGamesPlayed(): void
{
$scores =
"Allegoric Alaskans;Blithering Badgers;loss\n" .
"Devastating Donkeys;Allegoric Alaskans;loss\n" .
"Courageous Californians;Blithering Badgers;draw\n" .
"Allegoric Alaskans;Courageous Californians;win";
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" .
"Blithering Badgers | 2 | 1 | 1 | 0 | 4\n" .
"Courageous Californians | 2 | 0 | 1 | 1 | 1\n" .
"Devastating Donkeys | 1 | 0 | 0 | 1 | 0";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
public function testTiesSortedAlphabetically(): void
{
$scores =
"Courageous Californians;Devastating Donkeys;win\n" .
"Allegoric Alaskans;Blithering Badgers;win\n" .
"Devastating Donkeys;Allegoric Alaskans;loss\n" .
"Courageous Californians;Blithering Badgers;win\n" .
"Blithering Badgers;Devastating Donkeys;draw\n" .
"Allegoric Alaskans;Courageous Californians;draw";
$expected =
"Team | MP | W | D | L | P\n" .
"Allegoric Alaskans | 3 | 2 | 1 | 0 | 7\n" .
"Courageous Californians | 3 | 2 | 1 | 0 | 7\n" .
"Blithering Badgers | 3 | 0 | 1 | 2 | 1\n" .
"Devastating Donkeys | 3 | 0 | 1 | 2 | 1";
$this->assertEquals($expected, $this->tournament->tally($scores));
}
}