Skip to content

Instantly share code, notes, and snippets.

@ronssij
Last active April 16, 2024 12:21
Show Gist options
  • Save ronssij/f30a5976eda9fa1eb6e330b7c1c2e57b to your computer and use it in GitHub Desktop.
Save ronssij/f30a5976eda9fa1eb6e330b7c1c2e57b to your computer and use it in GitHub Desktop.

Revisions

  1. ronssij revised this gist Apr 16, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion roman_numerals.php
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@

    <?php

    $roman = ['i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000];

  2. ronssij revised this gist Apr 16, 2024. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions roman_numerals.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@


    $roman = ['i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000];

    $value = 'IX';
  3. ronssij created this gist Apr 16, 2024.
    20 changes: 20 additions & 0 deletions roman_numerals.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    $roman = ['i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000];

    $value = 'IX';
    $result = 0;
    $prevValue = 0;

    if (preg_match('/[^ivxlcdm]|i{4,}|x{4,}|c{4,}|m{4,}|v{2,}|l{2,}|d{2,}/i', $value)) {
    return "invalid format";
    }

    return str($value)->ucsplit('')
    ->reverse()
    ->values()
    ->map(fn ($item) => $roman[strtolower($item)])
    ->reduce(function ($carry, $item) use (&$prevValue) {
    $result = ($item >= $prevValue) ? $carry + $item : $carry - $item;
    $prevValue = $item;

    return $result;
    }, 0);