Dev Anony Dev Anony - 3 months ago 28
PHP Question

How to output Simple Array Sum challenge of HackerRank in PHP?

I was just trying to get familiar with HackerRank environment and practice some problems.

I was attempting its 2nd challenge in Algorithms>Warmups:
Simple Array Sum

I have solved it and its working fine on my local machine.

Code:
<?php

function testSum($n,$x)
{
$sum=0;
$x =explode(" ",$x);
for($i=0;i<$n;$i++)
{
$sum+=$x[$i];
}
echo $sum;
}
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
$arr_temp = fgets($handle);
$arr = explode(" ",$arr_temp);
array_walk($arr,'intval');

?>


But It keeps giving me same response every time:
Response on running code.

Please help me how to print results in hackerrank and what am I missing here. Thanks

Answer

I'm not the first one but let me try (mine works on hackerrank.com too :)

<?php
/* simple solution for https://www.hackerrank.com/challenges/simple-array-sum */

/* Read and parse input */
$handle = fopen ('php://stdin', 'r');
fscanf($handle, '%d', $n);
$numbers = explode(' ', fgets($handle));
array_walk($numbers, function (&$value) {
    $value = intval($value);
});

/* result: http://php.net/manual/en/function.array-sum.php */
echo array_sum($numbers);

Simple step by step explanation

  1. Read user input - check the examples in the documentation.
  2. fscanf is really not needed here. In our case it reads number from input and stores the value in the $n variable. Check format description in the docs.
  3. fgets($handle) reads a string. Next we split the string into array using explode. These are all very basic and often used PHP functions, make sure to get familiar with them and read the documentation.
  4. We walk (array_walk) through the array and convert all elements to integers. We use anonymous function in the example. This is a bit more advanced technique and might be skipped here.
  5. Finally we calculate and output the sum using array_sum function.
Comments