Sort by

recency

|

1288 Discussions

|

  • + 0 comments

    I wanted to do it the naive way without Googling what the valid permutations are.

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os"
        "strconv"
        "strings"
        "math"
    )
    
    func sum(s []int32) int32 {
        sum := int32(0)
        for i := range s {
            sum += s[i]
        }
        return sum
    }
    
    
    func isMagic(s [][]int32) bool {
        sums := []int32{
            sum(s[0]), sum(s[1]), sum(s[2]),
            s[0][0]+s[1][0]+s[2][0],                    
            s[0][1]+s[1][1]+s[2][1],                     
            s[0][2]+s[1][2]+s[2][2],                     
            s[0][0]+s[1][1]+s[2][2],                     
            s[0][2]+s[1][1]+s[2][0],                      
        }
        for i := range sums {
            if sums[i] != 15 {
                return false
            }
        }
        return true
    }
    
    func permutations(arr []int32)[][]int32{
        var helper func([]int32, int32)
        res := [][]int32{}
    
        helper = func(arr []int32, n int32){
            if n == 1{
                tmp := make([]int32, len(arr))
                copy(tmp, arr)
                res = append(res, tmp)
            } else {
                for i := 0; i < int(n); i++{
                    helper(arr, n - 1)
                    if n % 2 == 1{
                        tmp := arr[i]
                        arr[i] = arr[n - 1]
                        arr[n - 1] = tmp
                    } else {
                        tmp := arr[0]
                        arr[0] = arr[n - 1]
                        arr[n - 1] = tmp
                    }
                }
            }
        }
        helper(arr, int32(len(arr)))
        return res
    }
    
    func generateAllPossibleSquares() [][][]int32 {
        squares := permutations([]int32{1,2,3,4,5,6,7,8,9})
        validMagics := make([][][]int32, 8)
        validCounter := 0
        for _, s := range squares {
            square := [][]int32{s[0:3], s[3:6], s[6:9]}
            if isMagic(square) {
                validMagics[validCounter] = square
                validCounter += 1
            }
        }
        return validMagics
    }
    
    func cost(sq1 [][]int32, sq2 [][]int32) int32 {
        totalCost := int32(0)
        for i := range len(sq1) {
            for j := range len(sq1[i]) {
                totalCost += int32(math.Abs(float64(sq1[i][j] - sq2[i][j])))
            }
        }
        return totalCost
    } 
    
    /*
     * Complete the 'formingMagicSquare' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts 2D_INTEGER_ARRAY s as parameter.
     */
    
    func formingMagicSquare(s [][]int32) int32 {
        // First, we need a function that calculates all the various sums. 
        // To find the closest magic square, we calculate the difference between each intersecting row
        // The smallest cost should be the difference between intersecting rows
        minCost := int32(math.MaxInt32)
        validMagics := generateAllPossibleSquares()
        for i := range validMagics {
            newCost := cost(s, validMagics[i])
            if newCost < minCost {
                minCost = newCost
            }
        }
        return minCost
    
    }
    
    func main() {
        reader := bufio.NewReaderSize(os.Stdin, 16 * 1024 * 1024)
    
        stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
        checkError(err)
    
        defer stdout.Close()
    
        writer := bufio.NewWriterSize(stdout, 16 * 1024 * 1024)
    
        var s [][]int32
        for i := 0; i < 3; i++ {
            sRowTemp := strings.Split(strings.TrimRight(readLine(reader)," \t\r\n"), " ")
    
            var sRow []int32
            for _, sRowItem := range sRowTemp {
                sItemTemp, err := strconv.ParseInt(sRowItem, 10, 64)
                checkError(err)
                sItem := int32(sItemTemp)
                sRow = append(sRow, sItem)
            }
    
            if len(sRow) != 3 {
                panic("Bad input")
            }
    
            s = append(s, sRow)
        }
    
        result := formingMagicSquare(s)
    
        fmt.Fprintf(writer, "%d\n", result)
    
        writer.Flush()
    }
    
    func readLine(reader *bufio.Reader) string {
        str, _, err := reader.ReadLine()
        if err == io.EOF {
            return ""
        }
    
        return strings.TrimRight(string(str), "\r\n")
    }
    
    func checkError(err error) {
        if err != nil {
            panic(err)
        }
    }
    
  • + 1 comment

    Probably the simplest solution you could think of

    // All eight possible magic squares
    static const vector<vector<int>> squares[8] = {
        {
            { 8, 3, 4 },
            { 1, 5, 9 },
            { 6, 7, 2 }
        },
        {
            { 6, 7, 2 },
            { 1, 5, 9 },
            { 8, 3, 4 }
        },
        {
            { 4, 3, 8 },
            { 9, 5, 1 },
            { 2, 7, 6 }
        },
        {
            { 2, 7, 6 },
            { 9, 5, 1 },
            { 4, 3, 8 }
        },
        {
            { 6, 1, 8 },
            { 7, 5, 3 },
            { 2, 9, 4 }
        },
        {
            { 2, 9, 4 },
            { 7, 5, 3 },
            { 6, 1, 8 }
        },
        {
            { 8, 1, 6 },
            { 3, 5, 7 },
            { 4, 9, 2 }
        },
        {
            { 4, 9, 2 },
            { 3, 5, 7 },
            { 8, 1, 6 }
        }
    };
    
    int computeCost(const vector<vector<int>> &a, const vector<vector<int>> &b) {
        int cost = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                cost += abs(a[i][j] - b[i][j]);
            }
        }
        return cost;
    }
    
    int formingMagicSquare(vector<vector<int>> s) {
        int minCost = computeCost(s, squares[0]);
        
        for (int i = 1; i < 8; i++) {
            int c = computeCost(s, squares[i]);
            if (c < minCost) minCost = c;
        }
        
        return minCost;
    }
    
  • + 2 comments

    Hardware store offerings are designed to solve problems, whether practical or creative. Just like the concept of Forming a Magic Square, where each number must fit perfectly to create balance, the right tools and materials help bring harmony to any project. From basic repairs to complex builds, a reliable hardware store ensures precision, variety, and support, helping customers complete their tasks with efficiency while maintaining balance in both functionality and design.

  • + 0 comments

    Emergency Locksmith Leeds explains the concept of forming a magic square, a fascinating mathematical arrangement where the sums of numbers in each row, column, and diagonal are equal. Magic squares have been studied for centuries for their intriguing patterns and symmetry. They can vary in size and complexity, offering endless possibilities for puzzles and problem-solving. Understanding their structure enhances logical thinking, number skills, and creativity, making magic squares both educational and entertaining.

  • + 0 comments

    Emergency Locksmith Harrogate services provide fast, reliable solutions for lockouts, repairs, and security upgrades, ensuring your property remains safe and accessible. Just like Forming a Magic Square requires precision and careful planning, professional locksmiths approach every task with skill and accuracy. From handling urgent emergencies to installing advanced lock systems, their expertise guarantees peace of mind, keeping homes, offices, and vehicles secure while offering dependable, prompt, and trustworthy service whenever access or protection is needed.