Safe Array Index

Safe Array Index

Easy PHP PHP Error Handling 35 views
Explanation Complexity

Problem Statement

Given n integers and index i, print a[i] or OUT_OF_RANGE.

Input Format

Line1 n i. Line2 n integers.

Output Format

Value or OUT_OF_RANGE.

Example

4 2
10 20 30 40
30

Constraints

0

Input / Output Format

Input Format
Line1 n i. Line2 n integers.
Output Format
Value or OUT_OF_RANGE.
Constraints
0

Examples

Input:
4 2 10 20 30 40
Output:
30

Example Solution (Public)

PHP
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$idx=0; $n=intval($tokens[$idx++] ?? 0);
$i=intval($tokens[$idx++] ?? 0);
$a=[];
for($k=0;$k<$n;$k++) $a[] = $tokens[$idx++] ?? '0';
if($i<0 || $i>=$n) echo 'OUT_OF_RANGE';
else echo $a[$i];
?>

Official Solution Code

<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$idx=0; $n=intval($tokens[$idx++] ?? 0);
$i=intval($tokens[$idx++] ?? 0);
$a=[];
for($k=0;$k<$n;$k++) $a[] = $tokens[$idx++] ?? '0';
if($i<0 || $i>=$n) echo 'OUT_OF_RANGE';
else echo $a[$i];
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.