Recap: Simple Grid Exercise
Part of the Logic & Flow section of Coddy's PHP journey — lesson 32 of 68.
Challenge
EasyYou will receive one input: a 2D array representing a simple game grid in JSON format. The grid contains numbers representing different tile values. Read the input, convert the JSON string to a 2D array, and perform the following operations:
- Calculate and print the sum of all values in the grid
- Find and print the maximum value in the grid
- Count and print how many tiles have a value greater than 5
- Print the value located at row 1, column 2 (using 0-based indexing)
Print each result on a separate line in the exact order specified above.
Input format: One line containing a JSON array representing the game grid (example: [[3,7,2],[5,9,1],[8,4,6]])
Expected output:
- Line 1: Sum of all values
- Line 2: Maximum value
- Line 3: Count of tiles with value greater than 5
- Line 4: Value at row 1, column 2
Try it yourself
<?php
// Read the JSON input
$input = trim(fgets(STDIN));
// Convert JSON string to 2D array
// Important: Use (array) to ensure proper array conversion
$grid = json_decode($input, true);
// TODO: Write your code below
// 1. Calculate the sum of all values in the grid
// 2. Find the maximum value in the grid
// 3. Count how many tiles have a value greater than 5
// 4. Get the value at row 1, column 2
// Output the results (one per line)
// echo $sum . "\n";
// echo $max . "\n";
// echo $count . "\n";
// echo $value . "\n";
?>All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting