Skip to content

Instantly share code, notes, and snippets.

@NicolaBernini
Created August 1, 2020 06:49
Show Gist options
  • Save NicolaBernini/eaad0985ae4df44b45113555e6389e37 to your computer and use it in GitHub Desktop.
Save NicolaBernini/eaad0985ae4df44b45113555e6389e37 to your computer and use it in GitHub Desktop.
Solution to Hackerrank 2D Array - DS
@NicolaBernini
Copy link
Author

NicolaBernini commented Aug 1, 2020

Scala

Scala

import java.io._
import java.math._
import java.security._
import java.text._
import java.util._
import java.util.concurrent._
import java.util.function._
import java.util.regex._
import java.util.stream._

object Solution {

    // Complete the hourglassSum function below.
    def hourglassSum(arr: Array[Array[Int]]): Int = {
        (for (i <- 0 until arr.length-2; j <- 0 until arr(0).length-2 ) yield arr(i)(j) + arr(i)(j+1) + arr(i)(j+2) + arr(i+1)(j+1) + arr(i+2)(j) + arr(i+2)(j+1) + arr(i+2)(j+2)).max
    }

    def main(args: Array[String]) {
        val stdin = scala.io.StdIn

        val printWriter = new PrintWriter(sys.env("OUTPUT_PATH"))

        val arr = Array.ofDim[Int](6, 6)

        for (i <- 0 until 6) {
            arr(i) = stdin.readLine.split(" ").map(_.trim.toInt)
        }

        val result = hourglassSum(arr)

        printWriter.println(result)

        printWriter.close()
    }
}

Result

image

@NicolaBernini
Copy link
Author

Rust

// Solution to Hackerrank 2D Array 
// https://www.hackerrank.com/challenges/2d-array/problem

fn f_hourglass_count(a: &Vec<Vec<i32>>, i: usize, j: usize) -> i32 {
  if (i+2 >= a.len()) || (j+2 >= a[0].len()) {return 0; }
  return a[i][j] + a[i][j+1] + a[i][j+2] + 
         a[i+1][j+1] +
         a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]; 
}

fn get_max(a: &Vec<Vec<i32>>) -> (usize, usize, i32)
{
  let mut res = 0; 
  let mut best_i = 0; 
  let mut best_j = 0; 
  if a.len() == 0 {return (0,0,0);}
  for i in 0..a.len() {
    for j in 0..a[0].len() {
      let temp = f_hourglass_count(a,i,j); 
      if temp > res {best_i = i; best_j = j; res = temp;}
    }
  }
  return (best_i, best_j, res); 
}

fn main() {
  let a: Vec<Vec<i32>> = vec![ vec![1,2,3,1,2,3], vec![4,5,6,4,5,6], vec![7,8,9,7,8,9], vec![1,2,3,1,2,3], vec![4,5,6,4,5,6], vec![7,8,9,7,8,9] ]; 
  let res = get_max(&a); 
  println!("Max found at i={}, j={}, val={}", res.0, res.1, res.2); 
}

Result

image

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