Sort by

recency

|

1290 Discussions

|

  • + 0 comments

    Great discussion here — I found the insight about there being only eight valid 3×3 magic squares for the numbers 1-9 very helpful. That fact really simplifies the problem by turning it into a fixed comparison set. On a somewhat different note, while I was reading this I reflected on how the same principles of user-experience and efficient logic apply across tech domains. For example, I recently checked out the Black Hole Music APK — an Android app that emphasises smooth UI, ad-free listening, and high-quality audio. It reminded me that whether you’re solving a coding puzzle like designing a magic square or building a music app, attention to detail, performance, and clarity make the difference.

    Thanks for sharing all these approaches — they’re really helpful for understanding both the math and the implementation side of algorithmic challenges!

  • + 0 comments

    I first precomputed all magic squares. There's only one: 4 rotations and 4 mirrors, hence 8 representations of the same magic square. I then printed them and hard coded them.

    public static int formingMagicSquare(List<List<Integer>> s) {
    // Write your code here
    // precomputed all magic squares.
        int[][] allmagic = new int[][] {
        {2, 7, 6, 9, 5, 1, 4, 3, 8}, 
        {2, 9, 4, 7, 5, 3, 6, 1, 8}, 
        {4, 3, 8, 9, 5, 1, 2, 7, 6}, 
        {4, 9, 2, 3, 5, 7, 8, 1, 6}, 
        {6, 1, 8, 7, 5, 3, 2, 9, 4}, 
        {6, 7, 2, 1, 5, 9, 8, 3, 4}, 
        {8, 1, 6, 3, 5, 7, 4, 9, 2}, 
        {8, 3, 4, 1, 5, 9, 6, 7, 2}
        };
        int[] sint = new int[9];
        for (int y = 0; y < 3; y++) {
            for (int x = 0; x < 3; x++) {
                sint[x + y * 3] = s.get(y).get(x);
            }
        }
        int count = 9 * 9;
        for (int i = 0; i < allmagic.length;i++) {
            int mycount = 0;
            for (int j = 0; j < 9; j++) {
                mycount += Math.abs(allmagic[i][j] - sint[j]);
            }
            if (mycount < count) {
                count = mycount;
            }
        }
        return count;
    }
    
  • + 1 comment

    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.