Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Last active July 2, 2018 12:11
Show Gist options
  • Save earlonrails/f0533e9598c1467e27abf28d6c20c255 to your computer and use it in GitHub Desktop.
Save earlonrails/f0533e9598c1467e27abf28d6c20c255 to your computer and use it in GitHub Desktop.
Solution to 2D array problem from hackerrank in ES6 - https://www.hackerrank.com/challenges/2d-array/problem
#!/usr/bin/env node
// https://www.hackerrank.com/challenges/2d-array/problem
class HourGlass {
constructor(attrs, debug) {
this.attrs = attrs
this.debug = debug
this.value = this.compute()
}
compute() {
if (this.debug) {
console.log("attrs:", this.attrs)
console.log("topRow:", this.topRow())
console.log("middle:", this.middle())
console.log("botRow:", this.botRow())
}
return this.topRow() + this.middle() + this.botRow()
}
topRow() {
return this.attrs.topLeft + this.attrs.topMid + this.attrs.topRight
}
middle() {
return this.attrs.mid
}
botRow() {
return this.attrs.botLeft + this.attrs.botMid + this.attrs.botRight
}
}
class Matrix {
constructor(array, debug) {
this.array = array
this.debug = debug
}
findHourGlasses() {
// 1 1 1 0 0 0
// 0 1 0 0 0 0 <-- start at position 1,1 end at position 1,4
// 1 1 1 0 0 0
// 0 0 2 4 4 0
// 0 0 0 2 0 0
// 0 0 1 2 4 0
let arr = this.array
var maxHourGlass = {}
for (var i = 1; i < arr.length - 1; i++) {
let row = arr[i]
for (var j = 1; j < row.length - 1; j++) {
let hourGlass = new HourGlass({
topLeft: arr[i-1][j-1],
topMid: arr[i-1][j],
topRight: arr[i-1][j+1],
mid: arr[i][j],
botLeft: arr[i+1][j-1],
botMid: arr[i+1][j],
botRight: arr[i+1][j+1],
position: {y: i, x: j}
})
if (this.debug) console.log("compute:", hourGlass.value)
if (!maxHourGlass.hasOwnProperty("value") || maxHourGlass.value < hourGlass.value) {
maxHourGlass = hourGlass
}
}
}
return maxHourGlass
}
}
// var matrix = [
// [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]
// ]
// -6
var matrix = [
[-1,-1, 0,-9,-2,-2],
[-2,-1,-6,-8,-2,-5],
[-1,-1,-1,-2,-3,-4],
[-1,-9,-2,-4,-4,-5],
[-7,-3,-3,-2,-9,-9],
[-1,-3,-1,-2,-4,-5]
]
let hourGlassFinder = new Matrix(matrix)
console.dir(hourGlassFinder.findHourGlasses())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment