Skip to content

Instantly share code, notes, and snippets.

@vxzry
Last active March 19, 2018 03:54
Show Gist options
  • Save vxzry/f7d14c707ff0df6e9accad2f595ae34c to your computer and use it in GitHub Desktop.
Save vxzry/f7d14c707ff0df6e9accad2f595ae34c to your computer and use it in GitHub Desktop.
Hackerrank 30 Days of Code Day 11: 2D Arrays
<?php
/*
test input:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
*/
$handle = fopen ("php://stdin","r");
$arr = array();
$sum_list = array();
$top_bottom_count = 3;
// get contents
for($arr_i = 0; $arr_i < 6; $arr_i++) {
$arr_temp = fgets($handle);
array_push($arr, explode(" ",$arr_temp));
}
// loop through contents
for ($i=0; $i < count($arr) - 2; $i++){
for($j=0; $j <= count($arr[$i])-$top_bottom_count; $j++){
array_push($sum_list, getSum($arr, $i, $j, $top_bottom_count));
}
}
// print sum
echo max($sum_list);
function getSum($arr, $row, $col, $count){
$sum = 0;
for($i=0; $i<$count; $i++){
$sum += $arr[$row][$col+$i];
$sum += $arr[$row+2][$col+$i];
}
$sum += $arr[$row+1][$col+1];
return $sum;
}
?>
@vxzry
Copy link
Author

vxzry commented Mar 19, 2018

Challenge Name: Day 11: 2D Arrays

Objective
Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!

Context
Given a 6 x 6 2D Array, A:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

We define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:

a b c
  d
e f g

There are $16$ hourglasses in A, and an hourglass sum is the sum of an hourglass' values.

Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment