Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End PHP Challenge

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #33538
    mshort1985
    Member

    Hi folks, I have started searching the net for programming challenges just to test my self on what i’ve been learning, this is the first one I attempted. It seems simple but I was wondering if some more experienced Programmers might look over my solution and tell me if there would have been a more effient way to complete it. Thanks :)

    the problem is as follows:
    Your program should be able to open a text file and read its contents. The file will consist only of LOWERCASE letters and numbers 0-9. The file will be formatted such that there is only one alphanumeric character per line. Example file:

    5
    a
    n
    7
    4
    n
    6
    1
    0
    y
    w
    a

    Your program must read each line and store the data in a data structure of your choice. Parse through your structure and print out the following information:

    1. The sum of all the individual digits.
    2. How many times each character appeared in the file.

    Example output for the example above would be:

    Sum = 23
    a = 2
    n = 2
    w = 1
    y = 1

    Your program should work with any size file.

    and here is my solution:

    
    //read the file
    $myFile = "numbers.txt";
    $haystack = file_get_contents($myFile);

    //Form an array from the data gathered from the file
    $theData = str_split($haystack);

    //Add up the values and echo out the sum.
    echo "Sum: " . array_sum($theData) . "
    ";
    //Strip out any duplicate values from the array and then sort the array
    $theData = array_unique($theData);
    sort($theData);

    //remove the first value of the array to get rid of any Null values.
    array_shift($theData);

    //loop through the array counting how many times each value appears in the haystack string and then echoing them out.
    foreach($theData as $needle) {
    echo "$needle: " . substr_count($haystack, $needle) . "
    ";
    }

    ?>

    Thanks in advance :)

    #83525
    djpic
    Participant

    Looks very simple. Personally, I would have looped through each line of the text file, check each line if it is a integer or character. If it is was an integer, add it to a $sum variable. If it was a character, then place that in an array like this:



    $char[$currentLineValue] = $currentLineValue;
    $char[$currentLineValue]++;

    Then to display the results, echoed out the $sum and then:



    foreach($char as $character) {
    // echo out variables here
    }

    #83536
    ddliu
    Member

    Here is my solution:


    $file='numbers.txt';
    $fp=fopen($file,'r');

    $sum=0;
    $chars=array();

    //parse line by line to save memory
    while(false!==$line=fgets($fp)){
    $line=trim($line);
    if(is_numeric($line)){
    $sum+=$line;
    }
    else{
    if(!isset($chars[$line])){
    $chars[$line]=1;
    }
    else{
    $chars[$line]++;
    }
    }
    }

    //close file
    fclose($fp);

    //sort chars
    ksort($chars);

    //print result
    echo 'Sum: '.$sum.PHP_EOL;
    foreach($chars as $char=>$num){
    echo $char.':'.$num.PHP_EOL;
    }

    #83584
    mshort1985
    Member

    oh Nice, I didn’t know about the is_numeric() function :) yay learned something hehe. both are good solutions.

    #184789
    _monty
    Participant

    Try this…

    <?php
    $file_contents = trim(file_get_contents(‘/full/path/to/file.txt’));

    if($file_contents)
    {
    $sum = 0;
    $alpha_count_arr = array();
    $contents_to_arr = array_map(‘trim’,array_filter(explode(“\n”, $file_contents)));

    foreach ($contents_to_arr as $key => $value)
    {

    if(is_numeric($value))
    {
    $sum += $value;
    }
    elseif(ctype_alpha($value))
    {
    if(!isset($alpha_count_arr[$value]))
    {
    $alpha_count_arr[$value] = 1;
    }
    else
    {
    $alpha_count_arr[$value]++;
    }
    }

    }

    if(count($alpha_count_arr) > 0)
    {
    ksort($alpha_count_arr);
    foreach ($alpha_count_arr as $character => $count)
    {
    echo “$character = $count<br/>”;
    }
    }

    echo “<br/>Numeric value total: “.$sum;

    }
    ?>

    #185118
    chrisburton
    Participant

    Does anyone know of a website with these mini projects for PHP?

    #198597
    Taufik Nurrohman
    Participant
    <?php
    
    // Your program must read each line and
    // store the data in a data structure
    // of your choice.
    
    $content = file_get_contents('numbers.txt');
    
    $numbers = 0;
    $chars = array();
    
    $parts = explode("\n", $content);
    
    foreach($parts as $part) {
        $part = trim($part);
        // [1]. The sum of all the individual digits.
        if(is_numeric($part)) {
            $numbers += (int) $part;
        } else {
            if($part !== "") {
                $chars[] = $part;
            }
        }
    }
    
    // [2]. How many times each character appeared in the file.
    $chars = array_count_values($chars);
    
    ksort($chars); // sort alphabetically
    
    $str = 'Sum = ' . $numbers . "\n\n";
    
    foreach($chars as $k => $v) {
        $str .= $k . ' = ' . $v . "\n\n";
    }
    
    echo trim($str); // output!
    

    Demo: http://codepad.org/g2Kh9RG6

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘Back End’ is closed to new topics and replies.