Jump to content

Recommended Posts

Posted (edited)

So I applied to a job recently and was told I had to write a string calculator in php which would take as input a string "//[delimeter][delimeter2]\n" followed by a load of numbers separated by the delimeters for example //[***][,,,]\n1***3,,,2 The person I applied to claimed to be able to solve this by just adding all the numbers. But I don't think this is correct because the delimeter could contain numbers for instance

//[*1*][,2,]\n*1*3,2,2 . Then I thought I don't actually know what the delimeter is because the string can take 1 delimeter too ie //[delimeter]\n so the above //[*1*][,2,]\n*1*3,2,2 delimeter could actually be

*1*][,2, with the number being 1322. Is the question impossible?

 

from http://osherove.com/tdd-kata-1/

  1. Create a simple String calculator with a method int Add(string numbers)
    1. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”
    2. Start with the simplest test case of an empty string and move to 1 and two numbers
    3. Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
    4. Remember to refactor after each passing test
  2. Allow the Add method to handle an unknown amount of numbers
  3. Allow the Add method to handle new lines between numbers (instead of commas).
    1. the following input is ok: “1\n2,3” (will equal 6)
    2. the following input is NOT ok: “1,\n” (not need to prove it - just clarifying)
    1. Support different delimiters
    2. to change a delimiter, the beginning of the string will contain a separate line that looks like this: “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the default delimiter is ‘;’ .
    3. the first line is optional. all existing scenarios should still be supported
  4. Calling Add with a negative number will throw an exception “negatives not allowed” - and the negative that was passed.if there are multiple negatives, show all of them in the exception message stop here if you are a beginner. Continue if you can finish the steps so far in less than 30 minutes.
  5. Numbers bigger than 1000 should be ignored, so adding 2 + 1001 = 2
  6. Delimiters can be of any length with the following format: “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6
  7. Allow multiple delimiters like this: “//[delim1][delim2]\n” for example “//[*][%]\n1*2%3” should return 6.
  8. make sure you can also handle multiple delimiters with length longer than one char
Edited by fiveworlds
Posted (edited)

Is the question impossible?

You made it impossible :)

They didn't think about the case if delimiter is digit.

Delimiter is whatever is in string (optionally).

 

Then I thought I don't actually know what the delimeter is because the string can take 1 delimeter too ie //[delimeter]\n so the above //[*1*][,2,]\n*1*3,2,2 delimeter could actually be

*1*][,2, with the number being 1322.

String with delimiter "*1*" (3 chars delimiter) and such digits later should throw exception,

because delimiter can't be at first char..

It's like you would have ",3,2" (with default , delimiter)

 

 

 

This is actually easy task.

1) find whether you have redefined delimeters or not. Split them to 1st (delimeters) and 2nd part (data). Split delimeters to array.

2) if there are custom delimeters, replace each delimeter found in 2nd part by default delimeter f.e. ",". Use regular expressions.

3) Add numbers in 2nd part.

Edited by Sensei
Posted (edited)
Split delimeters to array.

 

But you can't do that. For instance

 

//[***][,,,]\n ok spilt on "//[" + "][" + "]\n"

//[//[***][,,,]\n][//[***][,,,]\n]\n not ok to spilt on "//[" + "][" + "]\n"

//[//[**1*][,,,]\n][//[**46*][,,,]\n[//[***][,,,]\n][//[*1*2][,,,[//[***][,,,]\n][//[***][,,,]\n not ok to spilt on "//[" + "][" + "]\n"

 

delimeter can be any length and contain numbers

 

 

They didn't think about the case if delimiter is digit.

Delimiter is whatever is in string (optionally).

 

I thought maybe an if(isset[delimeter]) might be appropriate but that's cheating

Edited by fiveworlds
Posted (edited)

If you have // at beginning, the first whole row is delimiter definition.

The rest is "string".

So make if string is starting with // then find the first \n,

and it's whole delimiter definition,

after \n there is "2nd part".

 

Then remove //

and split the rest by finding brackets [....] (split using reg exp! They will probably test your knowledge in this area)

where .... is our delimiter.

 

After that, if delimiter definition was f.e.

 

//[x][y][z]\n

 

There will be array of

x

y

z

Whatever they are.

 

I thought maybe an if(isset[delimeter]) might be appropriate but that's cheating

what? Do you even know PHP?

 

isset() is testing variable of PHP..

 

f.e.

 

You have index.php?xyz=123

 

$_GET[ 'xyz' ] contains 123

 

if( isset( $_GET[ 'xyz' ] ) ) will return true.

 

After using index.php (no params)

 

it'll return false.

Edited by Sensei
Posted (edited)

isset() is testing variable of PHP.. Yeah it is tests if I have been given a delimeter. For example

<?php
if((isset($_REQUEST["delimeter1"])&&($_REQUEST["delimeter2"]!=""))&&(isset($_REQUEST["delimeter2"])&&($_REQUEST["delimeter2"]!="")))
{

    $string=preg_replace("/\\\\n/", "\n", $_REQUEST['string']);
    $delimeter1=preg_replace("/\\\\n/", "\n", $_REQUEST["delimeter1"]);    
    $delimeter2=preg_replace("/\\\\n/", "\n", $_REQUEST["delimeter2"]);
    if((!(preg_match("/^[0-9]+$/", $string)))&(!(preg_match("/^[0-9]+$/", $var)))){
    if (strpos($string,"\\\\[{$delimeter1}][{$delimeter2}]\n") !== false) {

    $string=str_replace("\\\\[{$delimeter1}][{$delimeter2}]\n","",$string);
    $string=str_replace("{$delimeter2}","{$delimeter1}",$string);
    $string=strtolower($string);
    $string=explode($delimeter1,$string);
    $answer=0;
    $letters = array(    "a", "b","c","d","e","f","g","","i","j","k",
                "l","m","n","o","p","q","r","s","t","u","v",
                "w","x","y","z","¿","¼","½","¾","²","³","©",
                "®","™","¶","(",")","¦","†","|","}","{",">",
                "]","[","«","»","\\","/","—","‹","›","“","”",
                "‘","„","‚","!","*","¡","`","'","=","±","+",
                "÷","§","&","‰","%","°","•","·","‡","†","¦",
                "¬","_","–",";","…",":","¨","@","ß","$","£",
                "€","˜~","Ø","Ž","ž","Ý","ý","Ÿ","ÿ","×","ú",
                "ü","ù","û","š","^","ö","õ","ô","ó","ò","œ",
                "ó","ñ","Ï","ë","ê","é","è","Ð","ç","ª","æ",
                "å","µ","à","ã","á","â","Þ","¹","¯","¤","­",
                "¸","´","¢","¿","º","~"
                );

    foreach($string as $value){
        if(str_replace($letters, "", $value)<1000){
        $answer=$answer+str_replace($letters, "", $value);
        }
        else
        {
            echo $value." number larger than 1000 </br>";
        }
    }
    echo $answer;
    }
    else
    {
        echo "invalid string syntax";
    }

    }
    else{
        echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";
    }
}
elseif(isset($_REQUEST["delimeter1"])&&($_REQUEST["delimeter1"]!=""))
{

    $string=preg_replace("/\\\\n/", "\n", $_REQUEST['string']);
    $delimeter1=preg_replace("/\\\\n/", "\n", $_REQUEST["delimeter1"]);    
    if((!(preg_match("/^[0-9]+$/", $string)))){
    if (strpos($string,"\\\\[{$delimeter1}]\n") !== false) {

    $string=str_replace("\\\\[{$delimeter1}]\n","",$string);

    $string=strtolower ($string);
    $string=explode($delimeter1,$string);
        $answer=0;
    $letters = array(    "a", "b","c","d","e","f","g","","i","j","k",
                "l","m","n","o","p","q","r","s","t","u","v",
                "w","x","y","z","¿","¼","½","¾","²","³","©",
                "®","™","¶","(",")","¦","†","|","}","{",">",
                "]","[","«","»","\\","/","—","‹","›","“","”",
                "‘","„","‚","!","*","¡","`","'","=","±","+",
                "÷","§","&","‰","%","°","•","·","‡","†","¦",
                "¬","_","–",";","…",":","¨","@","ß","$","£",
                "€","˜~","Ø","Ž","ž","Ý","ý","Ÿ","ÿ","×","ú",
                "ü","ù","û","š","^","ö","õ","ô","ó","ò","œ",
                "ó","ñ","Ï","ë","ê","é","è","Ð","ç","ª","æ",
                "å","µ","à","ã","á","â","Þ","¹","¯","¤","­",
                "¸","´","¢","¿","º","~"
                );

    foreach($string as $value){
        if(str_replace($letters, "", $value)<1000){
        $answer=$answer+str_replace($letters, "", $value);
        }
        else
        {
            echo $value." number larger than 1000 </br>";
        }
    }
    echo $answer;
        
    }
    else{
        echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";
    }
    }
}
else
{
    echo "Delimeter must be set";
}
?>
<form>
delimeter1<input type="text" name="delimeter1" required="required"></br>
delimeter2<input type="text" name="delimeter2"></br></br>
string<input type="text" name="string"></br>
<input type="submit">
</form>
Edited by fiveworlds
Posted (edited)

It should be something like:

 

<?php

$string = $_GET[ 'data' ];

 

$result = Add( $string );

printf( "Result %d<br />\n", $result );

exit;

 

function Add( $string )

{

$result = 0;

[... here you put all your code...]

return( $result );

}

?>

 

Replace contents of Add() by your code.

 

Then test it, by going web browser to index.php?data=[string]

Edited by Sensei
Posted (edited)
$string = $_GET[ 'data' ];

 

you must use an if isset statement for $_GET or $_REQUEST otherwise it is a php error when it is not set. Also if you are doing further tests on data within that if statement you must put isset before them also $_REQUEST allows both GET and Post requests

 

if(isset($_GET['data']){

$string = $_GET[ 'data' ];

}

Edited by fiveworlds
Posted

This is far as I got so far

<?php
$testcases=new testcases();
class testcases
{
    function it_returns_0_for_an_empty_string(){
        add('');#0
    }

    function it_returns_a_single_number()
    {
        add("1");
    #shouldReturn(1);
    }
    function it_returns_an_error_on_negative_single_number()
    {
        add("-1");
    #shouldReturn(1);
    }

    function it_can_add_two_numbers()
    {
        add('1,2');
    #shouldReturn(3);
    }

    function it_can_add_multiple_numbers()
    {
        add('1,2,3,4,5');
    #shouldReturn(15);
    }

    function it_can_separate_numbers_by_new_lines()
    {
        add("\\\\[,][\n]\n1\n2,3",",","\n");
    #->shouldReturn(6);
    }


    function it_checks_strings_start_and_end_with_a_number()
    {
        echo "No delimeter check ";add("1,\n");echo "</br>";#should return syntax error
    echo "One delimeter check ";add("\\\\[***]\n1***\n2***3",'***');echo "</br>";#should return syntax error
    echo "Two delimeter check ";add("\\\\[***][,,,]\n1***\n2,,,3",'***',',,,');#should return syntax error
    }

    function it_ignores_numbers_above_1000()
    {
        add('1,2,1001,3');#->shouldReturn(6);    
    }

    function it_allows_any_length_delimeter()
    {
        add("\\\\[***]\n1***2***3",'***');#->shouldReturn(6);    
    }

    function it_allows_multiple_delimeters()
    {
        add("\\\\[*][%]\n1*2%3","*","%");#->shouldReturn(6);
    }

    function it_allows_multiple_delimeters_of_different_lengths()
    {
        add("\\\\[***][%]\n1***2%3","***","%");#shouldReturn(6);    
    }
    
    function it_fails_if_given_a_negative_number(){
        add("1,-2,3");#shouldReturn(6) and negative error
    }
    function it_allows_capital_letter_delimeters(){
        add("\\\\[AAA][,,,]\n1AAA2,,,3");#shouldReturn(6) and negative error
    }
}

function add($string,$delimeter1,$delimeter2){
    if(isset($string)&&("{$string}"!="")){
        if((isset($delimeter1)&&("{$delimeter1}"!=""))&&(isset($delimeter2)&&("{$delimeter2}"!="")))
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=preg_replace("/\\\\n/", "\n", $delimeter1);    
            $delimeter2=preg_replace("/\\\\n/", "\n", $delimeter2);
            if((!(preg_match("/^[0-9]+$/", $delimeter1)))&&(!(preg_match("/^[0-9]+$/", $delimeter1)))){
                if (strpos($string,"\\\\[{$delimeter1}][{$delimeter2}]\n") !== false) {
                    $string=str_replace("\\\\[{$delimeter1}][{$delimeter2}]\n","",$string);
                    $string=str_replace("{$delimeter2}","{$delimeter1}",$string);
                    if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                        $syntax=" --> syntax error";
                    }
                    
                    $string=explode($delimeter1,$string);
                    $answer=0;
                    $negatives="";
                    $letters = array(    "À", "Á", "Â", "Ã", "Ä", "Å","Æ", "Ç", "È", "É", "Ê", "Ë",
                    "Ì", "Í", "Î", "Ï", "Ð", "Ñ","Ò", "Ó", "Ô", "Õ", "Ö", "Ø",
                    "Ù", "Ú", "Û", "Ü", "Ý", "ß","à", "á", "â", "ã", "ä", "å",
                    "æ", "ç", "è", "é", "ê", "ë","ì", "í", "î", "ï", "ñ", "ò",
                    "ó", "ô", "õ", "ö", "ø", "ù","ú", "û", "ü", "ý", "ÿ", "A",
                    "a", "A", "a", "A", "a", "C","c", "C", "c", "C", "c", "C",
                    "c", "D", "d", "Ð", "d", "E","e", "E", "e", "E", "e", "E",
                    "e", "E", "e", "G", "g", "G","g", "G", "g", "G", "g", "H",
                    "h", "H", "h", "I", "i", "I","i", "I", "i", "I", "i", "I",
                    "i", "?", "?", "J", "j", "K","k", "L", "l", "L", "l", "L",
                    "l", "?", "?", "L", "l", "N","n", "N", "n", "N", "n", "?",
                    "O", "o", "O", "o", "O", "o","Œ", "œ", "R", "r", "R", "r",
                    "R", "r", "S", "s", "S", "s","S", "s", "Š", "š", "T", "t",
                    "T", "t", "T", "t", "U", "u","U", "u", "U", "u", "U", "u",
                    "U", "u", "U", "u", "W", "w","Y", "y", "Ÿ", "Z", "z", "Z",
                    "z", "Ž", "ž", "?", "ƒ", "O","o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U","u", "U", "u", "U", "u", "U",
                    "u", "?", "?", "?", "?", "?","?", "A", "A", "A", "A", "A",
                    "A", "AE", "C", "E", "E", "E","E", "I", "I", "I", "I", "D",
                    "N", "O", "O", "O", "O", "O","O", "U", "U", "U", "U", "Y",
                    "s", "a", "a", "a", "a", "a","a", "ae", "c", "e", "e", "e",
                    "e", "i", "i", "i", "i", "n","o", "o", "o", "o", "o", "o",
                    "u", "u", "u", "u", "y", "y","A", "a", "A", "a", "A", "a",
                    "C", "c", "C", "c", "C", "c","C", "c", "D", "d", "D", "d",
                    "E", "e", "E", "e", "E", "e","E", "e", "E", "e", "G", "g",
                    "G", "g", "G", "g", "G", "g","H", "h", "H", "h", "I", "i",
                    "I", "i", "I", "i", "I", "i","I", "i", "IJ", "ij", "J", "j",
                    "K", "k", "L", "l", "L", "l","L", "l", "L", "l", "l", "l",
                    "N", "n", "N", "n", "N", "n","n", "O", "o", "O", "o", "O",
                    "o", "OE", "oe", "R", "r", "R","r", "R", "r", "S", "s", "S", "s",
                    "S", "s", "S", "s", "T", "t", "T","t", "T", "t", "U", "u", "U", "u",
                    "U", "u", "U", "u", "U", "u", "U","u", "W", "w", "Y", "y", "Y", "Z",
                    "z", "Z", "z", "Z", "z", "s", "f","O", "o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U", "u","U", "u", "U", "u", "U", "u", "A",
                    "a", "AE", "ae", "O", "o","¿","¼","½","¾","²","³","©",
                    "®","™","¶","(",")","¦","†","|","}","{",">","]","[","«","»",
                    "\\","/","—","‹","›","“","”","‘","„","‚","!","*","¡","`","'",
                    "=","±","+","÷","§","&","‰","%","°","•","·","‡","†","¦",
                    "¬","_","–",";","…",":","¨","@","ß","$","£","€","˜~","œ",
                    "ª","æ","Þ","¹","¯","¤","¸","´","¢","¿","º","~"
                                );
                    foreach($string as $value){
                        if(str_replace($letters, "", $value)<1000){
                            if(str_replace($letters, "", $value)<0)
                            {
                                $negatives=$negatives.$value;
                                $value=str_replace($letters, "", $value)*-1;
                                
                            };
                        $answer=$answer+str_replace($letters, "", $value);
                        }
                        else{}
                    }
                    echo $answer;
                    if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
                    if(isset($syntax)){echo $syntax;}
                }
                else{echo "invalid string syntax";}
            }
            else{echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";}
        }
        elseif(isset($delimeter1)&&("{$delimeter1}"!=""))
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=preg_replace("/\\\\n/", "\n", $delimeter1);    
            if((!(preg_match("/^[0-9]+$/", $delimeter1)))){
                if (strpos($string,"\\\\[{$delimeter1}]\n") !== false) {
                    $string=str_replace("\\\\[{$delimeter1}]\n","",$string);
                    if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                        $syntax=" --> syntax error";
                    }
                    
                    $string=explode($delimeter1,$string);
                    $negatives="";
                        $answer=0;
                    $letters = array(    "À", "Á", "Â", "Ã", "Ä", "Å","Æ", "Ç", "È", "É", "Ê", "Ë",
                    "Ì", "Í", "Î", "Ï", "Ð", "Ñ","Ò", "Ó", "Ô", "Õ", "Ö", "Ø",
                    "Ù", "Ú", "Û", "Ü", "Ý", "ß","à", "á", "â", "ã", "ä", "å",
                    "æ", "ç", "è", "é", "ê", "ë","ì", "í", "î", "ï", "ñ", "ò",
                    "ó", "ô", "õ", "ö", "ø", "ù","ú", "û", "ü", "ý", "ÿ", "A",
                    "a", "A", "a", "A", "a", "C","c", "C", "c", "C", "c", "C",
                    "c", "D", "d", "Ð", "d", "E","e", "E", "e", "E", "e", "E",
                    "e", "E", "e", "G", "g", "G","g", "G", "g", "G", "g", "H",
                    "h", "H", "h", "I", "i", "I","i", "I", "i", "I", "i", "I",
                    "i", "?", "?", "J", "j", "K","k", "L", "l", "L", "l", "L",
                    "l", "?", "?", "L", "l", "N","n", "N", "n", "N", "n", "?",
                    "O", "o", "O", "o", "O", "o","Œ", "œ", "R", "r", "R", "r",
                    "R", "r", "S", "s", "S", "s","S", "s", "Š", "š", "T", "t",
                    "T", "t", "T", "t", "U", "u","U", "u", "U", "u", "U", "u",
                    "U", "u", "U", "u", "W", "w","Y", "y", "Ÿ", "Z", "z", "Z",
                    "z", "Ž", "ž", "?", "ƒ", "O","o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U","u", "U", "u", "U", "u", "U",
                    "u", "?", "?", "?", "?", "?","?", "A", "A", "A", "A", "A",
                    "A", "AE", "C", "E", "E", "E","E", "I", "I", "I", "I", "D",
                    "N", "O", "O", "O", "O", "O","O", "U", "U", "U", "U", "Y",
                    "s", "a", "a", "a", "a", "a","a", "ae", "c", "e", "e", "e",
                    "e", "i", "i", "i", "i", "n","o", "o", "o", "o", "o", "o",
                    "u", "u", "u", "u", "y", "y","A", "a", "A", "a", "A", "a",
                    "C", "c", "C", "c", "C", "c","C", "c", "D", "d", "D", "d",
                    "E", "e", "E", "e", "E", "e","E", "e", "E", "e", "G", "g",
                    "G", "g", "G", "g", "G", "g","H", "h", "H", "h", "I", "i",
                    "I", "i", "I", "i", "I", "i","I", "i", "IJ", "ij", "J", "j",
                    "K", "k", "L", "l", "L", "l","L", "l", "L", "l", "l", "l",
                    "N", "n", "N", "n", "N", "n","n", "O", "o", "O", "o", "O",
                    "o", "OE", "oe", "R", "r", "R","r", "R", "r", "S", "s", "S", "s",
                    "S", "s", "S", "s", "T", "t", "T","t", "T", "t", "U", "u", "U", "u",
                    "U", "u", "U", "u", "U", "u", "U","u", "W", "w", "Y", "y", "Y", "Z",
                    "z", "Z", "z", "Z", "z", "s", "f","O", "o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U", "u","U", "u", "U", "u", "U", "u", "A",
                    "a", "AE", "ae", "O", "o","¿","¼","½","¾","²","³","©",
                    "®","™","¶","(",")","¦","†","|","}","{",">","]","[","«","»",
                    "\\","/","—","‹","›","“","”","‘","„","‚","!","*","¡","`","'",
                    "=","±","+","÷","§","&","‰","%","°","•","·","‡","†","¦",
                    "¬","_","–",";","…",":","¨","@","ß","$","£","€","˜~","œ",
                    "ª","æ","Þ","¹","¯","¤","¸","´","¢","¿","º","~"
                                );
                    foreach($string as $value){
                        if(str_replace($letters, "", $value)<1000){
                            if(str_replace($letters, "", $value)<0)
                            {
                                $negatives=$negatives.$value.",";
                                $value=str_replace($letters, "", $value)*-1;                        
                            };
                        $answer=$answer+str_replace($letters, "", $value);
                        }
                        else
                        {}
                    }
                    echo $answer;
                    if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
                    if(isset($syntax)){echo $syntax;}
                }
                else{echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";}
                
            }
        }
        elseif($string!="")
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=",";    
            $string=str_replace("\\\\[{$delimeter1}]\n","",$string);
            if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                $syntax=" --> syntax error";
            }
            
            $string=explode($delimeter1,$string);
            $negatives="";
            $answer=0;
            $letters = array(    "À", "Á", "Â", "Ã", "Ä", "Å","Æ", "Ç", "È", "É", "Ê", "Ë",
                    "Ì", "Í", "Î", "Ï", "Ð", "Ñ","Ò", "Ó", "Ô", "Õ", "Ö", "Ø",
                    "Ù", "Ú", "Û", "Ü", "Ý", "ß","à", "á", "â", "ã", "ä", "å",
                    "æ", "ç", "è", "é", "ê", "ë","ì", "í", "î", "ï", "ñ", "ò",
                    "ó", "ô", "õ", "ö", "ø", "ù","ú", "û", "ü", "ý", "ÿ", "A",
                    "a", "A", "a", "A", "a", "C","c", "C", "c", "C", "c", "C",
                    "c", "D", "d", "Ð", "d", "E","e", "E", "e", "E", "e", "E",
                    "e", "E", "e", "G", "g", "G","g", "G", "g", "G", "g", "H",
                    "h", "H", "h", "I", "i", "I","i", "I", "i", "I", "i", "I",
                    "i", "?", "?", "J", "j", "K","k", "L", "l", "L", "l", "L",
                    "l", "?", "?", "L", "l", "N","n", "N", "n", "N", "n", "?",
                    "O", "o", "O", "o", "O", "o","Œ", "œ", "R", "r", "R", "r",
                    "R", "r", "S", "s", "S", "s","S", "s", "Š", "š", "T", "t",
                    "T", "t", "T", "t", "U", "u","U", "u", "U", "u", "U", "u",
                    "U", "u", "U", "u", "W", "w","Y", "y", "Ÿ", "Z", "z", "Z",
                    "z", "Ž", "ž", "?", "ƒ", "O","o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U","u", "U", "u", "U", "u", "U",
                    "u", "?", "?", "?", "?", "?","?", "A", "A", "A", "A", "A",
                    "A", "AE", "C", "E", "E", "E","E", "I", "I", "I", "I", "D",
                    "N", "O", "O", "O", "O", "O","O", "U", "U", "U", "U", "Y",
                    "s", "a", "a", "a", "a", "a","a", "ae", "c", "e", "e", "e",
                    "e", "i", "i", "i", "i", "n","o", "o", "o", "o", "o", "o",
                    "u", "u", "u", "u", "y", "y","A", "a", "A", "a", "A", "a",
                    "C", "c", "C", "c", "C", "c","C", "c", "D", "d", "D", "d",
                    "E", "e", "E", "e", "E", "e","E", "e", "E", "e", "G", "g",
                    "G", "g", "G", "g", "G", "g","H", "h", "H", "h", "I", "i",
                    "I", "i", "I", "i", "I", "i","I", "i", "IJ", "ij", "J", "j",
                    "K", "k", "L", "l", "L", "l","L", "l", "L", "l", "l", "l",
                    "N", "n", "N", "n", "N", "n","n", "O", "o", "O", "o", "O",
                    "o", "OE", "oe", "R", "r", "R","r", "R", "r", "S", "s", "S", "s",
                    "S", "s", "S", "s", "T", "t", "T","t", "T", "t", "U", "u", "U", "u",
                    "U", "u", "U", "u", "U", "u", "U","u", "W", "w", "Y", "y", "Y", "Z",
                    "z", "Z", "z", "Z", "z", "s", "f","O", "o", "U", "u", "A", "a", "I",
                    "i", "O", "o", "U", "u", "U", "u","U", "u", "U", "u", "U", "u", "A",
                    "a", "AE", "ae", "O", "o","¿","¼","½","¾","²","³","©",
                    "®","™","¶","(",")","¦","†","|","}","{",">","]","[","«","»",
                    "\\","/","—","‹","›","“","”","‘","„","‚","!","*","¡","`","'",
                    "=","±","+","÷","§","&","‰","%","°","•","·","‡","†","¦",
                    "¬","_","–",";","…",":","¨","@","ß","$","£","€","˜~","œ",
                    "ª","æ","Þ","¹","¯","¤","¸","´","¢","¿","º","~"
                        );
            foreach($string as $value){
                if(str_replace($letters, "", $value)<1000){
                    if(str_replace($letters, "", $value)<0)
                    {
                        $negatives=$negatives.$value.",";
                        $value=str_replace($letters, "", $value)*-1;                        
                    };
                $answer=$answer+str_replace($letters, "", $value);
                }
                else
                {}
            }
            echo $answer;
            if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
            if(isset($syntax)){echo $syntax;}
            

        }
        else{echo "0";}
    }
    else{echo "0";}
}
if(isset($_REQUEST['delimeter1'])&&("{$_REQUEST['delimeter1']}"!="")&&isset($_REQUEST['delimeter2'])&&("{$_REQUEST['delimeter2']}"!=""))
{
add($_REQUEST['string'],$_REQUEST['delimeter1'],$_REQUEST['delimeter2']);
}
elseif(isset($_REQUEST['delimeter1'])&&("{$_REQUEST['delimeter1']}"!=""))
{
add($_REQUEST['string'],$_REQUEST['delimeter1']);
}
elseif(isset($_REQUEST['string'])){
add($_REQUEST['string']);
}

echo "</br>Test cases</br>";
$testcases->it_returns_0_for_an_empty_string();echo "</br>";
$testcases->it_returns_a_single_number();echo "</br>";
$testcases->it_returns_an_error_on_negative_single_number();echo "</br>";
$testcases->it_checks_strings_start_and_end_with_a_number();echo"</br>";
$testcases->it_can_add_two_numbers();echo "</br>";
$testcases->it_can_add_multiple_numbers();echo "</br>";
$testcases->it_can_separate_numbers_by_new_lines();echo "</br>";
$testcases->it_ignores_numbers_above_1000();echo "</br>";
$testcases->it_allows_any_length_delimeter();echo "</br>";
$testcases->it_allows_multiple_delimeters();echo "</br>";
$testcases->it_allows_multiple_delimeters_of_different_lengths();echo "</br>";
$testcases->it_fails_if_given_a_negative_number();echo "</br>";
$testcases->it_allows_capital_letter_delimeters();echo "</br>";
?>
<form>
String<input type="text" name="string"></br>
Delimeter1<input type="text" name="delimeter1"></br>
Delimeter2<input type="text" name="delimeter2"></br>
<input type="submit">
</form>
  • 2 weeks later...
Posted

Why are you using a huge array of letters? Beyond the fact that this increases the size and operation of your code, it's also insufficient.

 

I mean, if you go at it with this type of thinking, then you're missing the *entire* range of Unicode, too. I could set up a delimiter that's written in Russian letters, or Hebrew letters, or Arabic letters.

 

This is a good way of falling into an endless pit of language-despair ;)

 

I think that if you actually need recognizable letters, you should go with unicode *ranges* in regexp, which would include all of the actual characters that are valid.

 

But again -- why do you even need those at all?

Posted (edited)
I mean, if you go at it with this type of thinking, then you're missing the *entire* range of Unicode, too. I could set up a delimiter that's written in Russian letters, or Hebrew letters, or Arabic letters.

No I am not. That's the finished code. You could add support for russian numbers etc if you want

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
function unichr($i){return iconv('UCS-4LE', 'UTF-8', pack('V', $i));}
function add($string,$delimeter1,$delimeter2){
    if(isset($string)&&("{$string}"!="")){
        if((isset($delimeter1)&&("{$delimeter1}"!=""))&&(isset($delimeter2)&&("{$delimeter2}"!="")))
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=preg_replace("/\\\\n/", "\n", $delimeter1);    
            $delimeter2=preg_replace("/\\\\n/", "\n", $delimeter2);
            if((!(preg_match("/^[0-9]+$/", $delimeter1)))&&(!(preg_match("/^[0-9]+$/", $delimeter1)))){
                if (strpos($string,"\\\\[{$delimeter1}][{$delimeter2}]\n") !== false) {
                    $string=str_replace("\\\\[{$delimeter1}][{$delimeter2}]\n","",$string);
                    $string=str_replace("{$delimeter2}","{$delimeter1}",$string);
                    if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                        $syntax=" --> syntax error";
                    }
                    
                    $string=explode($delimeter1,$string);
                    $answer=0;
                    $negatives="";
                    $codeunits = array();
                    for ($i = 0; $i<0xD800; $i++)$codeunits[] = unichr($i);
                    for ($i = 0xE000; $i<0xFFFF; $i++)$codeunits[] = unichr($i);
                    $letters = implode($codeunits);
                    $numbers = array("0","1","2","3","4","5","6","7","8","9","-");
                    $letters = str_replace($numbers,"",$numbers);
                    foreach($string as $value){
                        if(str_replace($letters, "", $value)<1000){
                            if(str_replace($letters, "", $value)<0)
                            {
                                $negatives=$negatives.$value;
                                $value=str_replace($letters, "", $value)*-1;
                                
                            };
                        $answer=$answer+str_replace($letters, "", $value);
                        }
                        else{}
                    }
                    echo $answer;
                    if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
                    if(isset($syntax)){echo $syntax;}
                }
                else{echo "invalid string syntax";}
            }
            else{echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";}
        }
        elseif(isset($delimeter1)&&("{$delimeter1}"!=""))
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=preg_replace("/\\\\n/", "\n", $delimeter1);    
            if((!(preg_match("/^[0-9]+$/", $delimeter1)))){
                if (strpos($string,"\\\\[{$delimeter1}]\n") !== false) {
                    $string=str_replace("\\\\[{$delimeter1}]\n","",$string);
                    if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                        $syntax=" --> syntax error";
                    }
                    
                    $string=explode($delimeter1,$string);
                    $negatives="";
                        $answer=0;
                    for ($i = 0; $i<0xD800; $i++)$codeunits[] = unichr($i);
                    for ($i = 0xE000; $i<0xFFFF; $i++)$codeunits[] = unichr($i);
                    $letters = implode($codeunits);
                    $numbers = array("0","1","2","3","4","5","6","7","8","9","-");
                    $letters = str_replace($numbers,"",$numbers);
                    foreach($string as $value){
                        if(str_replace($letters, "", $value)<1000){
                            if(str_replace($letters, "", $value)<0)
                            {
                                $negatives=$negatives.$value.",";
                                $value=str_replace($letters, "", $value)*-1;                        
                            };
                        $answer=$answer+str_replace($letters, "", $value);
                        }
                        else
                        {}
                    }
                    echo $answer;
                    if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
                    if(isset($syntax)){echo $syntax;}
                }
                else{echo "Invalid Delimeter Syntax, Delimeter cannot only contain numbers";}
                
            }
        }
        elseif($string!="")
        {
            $string=preg_replace("/\\\\n/", "\n", $string);
            $delimeter1=",";    
            $string=str_replace("\\\\[{$delimeter1}]\n","",$string);
            if (str_replace("{$delimeter1}\n","{$delimeter}", $string)!="{$string}") {
                $syntax=" --> syntax error";
            }
            
            $string=explode($delimeter1,$string);
            $negatives="";
            $answer=0;
            for ($i = 0; $i<0xD800; $i++)$codeunits[] = unichr($i);
            for ($i = 0xE000; $i<0xFFFF; $i++)$codeunits[] = unichr($i);
            $letters = implode($codeunits);
            $numbers = array("0","1","2","3","4","5","6","7","8","9","-");
            $letters = str_replace($numbers,"",$numbers);
            foreach($string as $value){
                if(str_replace($letters, "", $value)<1000){
                    if(str_replace($letters, "", $value)<0)
                    {
                        $negatives=$negatives.$value.",";
                        $value=str_replace($letters, "", $value)*-1;                        
                    };
                $answer=$answer+str_replace($letters, "", $value);
                }
                else
                {}
            }
            echo $answer;
            if($negatives!=""){echo " ---> Error Negative Number Array ".$negatives;}
            if(isset($syntax)){echo $syntax;}
            

        }
        else{echo "0";}
    }
    else{echo "0";}
}
if(isset($_REQUEST['delimeter1'])&&("{$_REQUEST['delimeter1']}"!="")&&isset($_REQUEST['delimeter2'])&&("{$_REQUEST['delimeter2']}"!=""))
{
add($_REQUEST['string'],$_REQUEST['delimeter1'],$_REQUEST['delimeter2']);
}
elseif(isset($_REQUEST['delimeter1'])&&("{$_REQUEST['delimeter1']}"!=""))
{
add($_REQUEST['string'],$_REQUEST['delimeter1']);
}
elseif(isset($_REQUEST['string'])){
add($_REQUEST['string']);
}

?>
<form>
String<input type="text" name="string"></br>
Delimeter1<input type="text" name="delimeter1"></br>
Delimeter2<input type="text" name="delimeter2"></br>
<input type="submit">
</form>
Edited by fiveworlds

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.