How to take input?

Viewed 283

I have started to practice coding problems (hackerearth.com) in PHP to increase my problem-solving skill.
As I saw, most of the coding problems are asked for taking input and then output the correct answer based on entered input.

Eg : Input-

  1. The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
  2. The next line consists of N space separated integers , denoting the elements of the array A.

Till now, I know -

 fscanf(STDIN, "%d %d\n", $n, $k); //takes N and K

But I don't know how to take an array of size N.

Please help me how to take array of size N. Then It will help me to code further. Else I will just stuck on taking input.

EDIT:

Please help me any PHP pro coder.

EDIT 2:

The problem on which I am still stuck is given below -
Coding challenge -
Monk and Rotation Monk loves to preform different operations on arrays, and so being the principal of Hackerearth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
enter image description here enter image description here

EDIT 3 -

Problem can be found here.
What I have tried till know to solve this problem-

fscanf(STDIN, "%s\n", $t);
fscanf(STDIN, "%s %s\n", $n, $k);
//taking 5 numbers seperated by space.
fscanf(STDIN, "%d %d %d %d %d\n", $item1,$item2,$item3,$item4,$item5);

$arr = [$item1,$item2,$item3,$item4,$item5];
for($i = 0; $i<$k; $i++){
    array_unshift($arr, array_pop($arr));
}
echo implode(' ', $arr);
2 Answers

You could use readline to read in the space-separated integers, then just split at the spaces to get an array. Note that the array elements will be of type string.

// input string
$string = readline();

// turn into an array
$array = explode(" ", $string);

In hackerearth for PHP you can do something like this -

function getMyInput($n)
{
    echo '<pre>';
    print_r($n);
}

$t = fgets(STDIN);

for ($t_itr = 0; $t_itr < $t; $t_itr++) {
    $n[] = fgets(STDIN);  
}
getMyInput($n);

Reference link

PHP standard input?

What does this code mean "ofstream fout(getenv("OUTPUT_PATH"));"

https://www.php.net/manual/en/function.fgets.php https://www.php.net/manual/en/function.intval.php

Explanation

Use fgets to read a line from the input using STDIN (I/O reading) then iterate from zero to the maximum provided INPUT and assign those values into a variable.
create a custom method and pass the I/O data (array variable) as an argument to make your own logic for problem-solving.

Related