ianadiwibowo/central-park

View on GitHub
hackerrank/forming_a_magic_square/main_trial_01.gox

Summary

Maintainability
Test Coverage
package main

func FormingMagicSquare(square [][]int32) int32 {
    // fmt.Println("isMagicSquare(square)", isMagicSquare(square))
    makeDistinct(&square)
    return 1
}

func calculateCost(before, after [][]int32) int32 {
    var totalCost int32
    for i, brow := range before {
        for j, b := range brow {
            // fmt.Println("b,a:", b, after[i][j])
            cost := b - after[i][j]
            if cost < 0 {
                cost = -cost
            }
            totalCost += cost
        }
    }
    return totalCost
}

func isMagicSquare(square [][]int32) bool {
    if !isDistinct(square) {
        return false
    }

    var magicConstant int32

    // // Diagonals
    // 00 11 22
    // 20 11 02
    var dia001122Sum int32
    for rc := 0; rc < 3; rc++ {
        dia001122Sum += square[rc][rc]
    }
    magicConstant = dia001122Sum
    // fmt.Println("Dia 001122:", dia001122Sum)

    var dia201102Sum int32
    for rc := 0; rc < 3; rc++ {
        dia201102Sum += square[2-rc][rc]
    }
    // fmt.Println("Dia 201102:", dia201102Sum)
    if dia201102Sum != magicConstant {
        return false
    }

    // Rows
    // 00 01 02
    // 10 11 12
    // 20 21 22
    for r := 0; r < 3; r++ {
        var rowSum int32
        for c := 0; c < 3; c++ {
            rowSum += square[r][c]
        }
        // fmt.Println("Row:", r, rowSum)
        if rowSum != magicConstant {
            return false
        }
    }

    // Columns
    // 00 10 20
    // 01 11 21
    // 02 12 22
    for c := 0; c < 3; c++ {
        var colSum int32
        for r := 0; r < 3; r++ {
            colSum += square[r][c]
        }
        // fmt.Println("Col", c, colSum)
        if colSum != magicConstant {
            return false
        }
    }

    return true
}

func isDistinct(square [][]int32) bool {
    counter := make(map[int32]int)
    for _, row := range square {
        for _, col := range row {
            if col < 1 || col > 9 {
                return false
            }
            counter[col]++
            if counter[col] > 1 {
                return false
            }
        }
    }

    return true
}