Forming a Magic Square

  • + 0 comments

    I have no clue how you supossed to figure this out on your own without serious matrix theory knowladge, and the knowladge of this silly trivia magic array, here is the info: There are fixed 9 numbers in 3x3 magic array, there is no other choice. Thje example gives this. The only different arrays can either 90 degree rotations of this magic array. Or a reflection on the middle, then this can also be rotated 90 degrees 3 times to get different versions. Good luck figuring this out on an interview.. ???

    int matrix_diff(vector>& A, vector>& B){ int diff=0; for(int i=0;i

    void transpose(vector>& A){ for(int i=0; i

    void reflect(vector>& A){ for(int i=0; i

    int formingMagicSquare(vector> s) { std::vector> magic = {{8,3,4},{1,5,9},{6,7,2}}; //there is only one magic array, and its 8 versions, by 3* 90degree rotation, then 1 reflection and 3rotations again //make another version, then compare diff to s, and record minimum; int min_global_diff=matrix_diff(s, magic);

    //try 3 rotations
    auto magic_rotation = magic;
    for(int rot=0; rot<4; rot++){ //do a 90 degree rotatiom by transpose+reflect
        transpose(magic_rotation);
        reflect(magic_rotation);
        min_global_diff = min(min_global_diff, matrix_diff(s, magic_rotation));
    }
    
    //now just do 1 reflection before 3 rotations again
    auto magic_reflect_rot = magic; 
    reflect(magic_reflect_rot); 
    //again 3 90 degree rotations
    for(int rot=0; rot<4; rot++){ //do a 90 degree rotatiom by transpose+reflect
        transpose(magic_reflect_rot);
        reflect(magic_reflect_rot);
        min_global_diff = min(min_global_diff, matrix_diff(s, magic_reflect_rot));
    }
    
    return min_global_diff;
    

    }