[Question]
  [
You are given a \$3\times3\$ square matrix where each cell is any digit between \$0\$ and \$9\$ except \$7\$. Your task is to figure out the *minimum* number of digits that must be replaced with \$7\$'s so that the sums of the digits in each row and each column are the same.
**NB:** There is no constraint whatsoever on the diagonals, so we end up with a semi-magical square.
## Examples
Here is a matrix where three digits need to be turned into \$7\$'s so that all sums are \$20\$:
$$\begin{pmatrix}8&6&6\\1&5&8\\6&9&5\end{pmatrix}\rightarrow\begin{pmatrix}\color{red}7&6&\color{red}7\\\color{red}7&5&8\\6&9&5\end{pmatrix}$$
In this one, only one digit needs to be replaced with a \$7\$ so that all sums are \$13\$:
$$\begin{pmatrix}9&2&2\\0&9&4\\4&2&9\end{pmatrix}\rightarrow\begin{pmatrix}9&2&2\\0&9&4\\4&2&\color{red}7\end{pmatrix}$$
And for this one, our only option is to replace all digits with \$7\$'s:
$$\begin{pmatrix}0&6&8\\3&6&1\\8&4&0\end{pmatrix}\rightarrow\begin{pmatrix}\color{red}7&\color{red}7&\color{red}7\\\color{red}7&\color{red}7&\color{red}7\\\color{red}7&\color{red}7&\color{red}7\end{pmatrix}$$
So the expected outputs for the above examples are \$3\$, \$1\$ and \$9\$ respectively.
## Rules
* Because the size of the matrix is fixed, you may take input as a flattened array or 9 distinct arguments.
* Because we're dealing with digits exclusively, you may also take a string of 9 characters.
* The input matrix may already fulfill the sum constraints, in which case the expected answer is \$0\$.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
```
[[9,4,3],[3,4,9],[4,8,4]] -> 0
[[5,1,3],[3,1,5],[1,2,1]] -> 1
[[3,9,6],[8,5,5],[8,4,0]] -> 2
[[5,3,5],[1,9,5],[3,3,3]] -> 2
[[8,3,0],[8,0,8],[0,8,4]] -> 3
[[1,5,2],[5,9,5],[6,5,3]] -> 4
[[3,0,8],[1,8,0],[1,3,8]] -> 4
[[3,3,0],[5,1,9],[9,9,5]] -> 5
[[2,4,5],[5,3,4],[4,4,8]] -> 6
[[3,0,3],[8,3,5],[8,3,4]] -> 9
```
  
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 29 bytes
```
∧ℕ≜.&{|∧7}ᵐ²{+ᵛS&\+ᵛS&c{7}ˢl}
```
[Try it online!](https://tio.run/##PU@hDsIwFPwVgpjhQdp1hdbwE8gyAQgQJCQYQsYMIQQcBgUKgyUkGCSWr1h/ZNzeGtTd69293hsvR5PZer6YxmW2ajba/UZzFfn9w2@3xfuYF69T6Q93vzv747UTZRsMver188xaxesyiIY1TLJe/r3N87J0zllKSKXkFNACEzKUpCBOkwyKJA2UFJNkRZGlLoghzQoSJEJGBa9lVJgVKwZMsFeQAYr/P9hOMYgOmS5mFf6pvRJewagw10q9repYtbacrZQYXTQruIjvSf4ZwfeY0NGwI01/ "Brachylog – Try It Online")
Or the much faster version with the last two constraint flipped for +2 bytes:
```
∧ℕ≜.&{|∧7}ᵐ²{c{7}ˢl.&+ᵛS&\+ᵛS∧}
```
[Try it online!](https://tio.run/##PU@hDsIwFPwVgpjhQdp1hdbwE8gyAQgQJCQYQsYMIQQcBgUKgyUkGCSWr1h/ZNzeGtTd69293hsvR5PZer6YxmW2ajba/UZzFfn9w2@3xfuYF69T6Q93vzv747UTZRsMver188wmWS//3uadqFW8LoNoyAA9L0vnnKWEVEpOAS0wIUNJCuI0yaBI0kBJMUlWFFnqghjSrCBBImRU8FpGhVmxYsAEewUZoPj/g@0Ug@iQ6WJW4Z/aK@EVjApzrdTbqo5Va8vZSonRRbOCi/ie5J8RfI8JHQ070vQH "Brachylog – Try It Online")
A problem for Brachylog is that the usual way to try the different 7s `{|∧7}²` would lead to the following search sequence:
```
[[5,3,5],[1,9,5],[3,3,3]]
[[5,3,5],[1,9,5],[3,3,7]]
[[5,3,5],[1,9,5],[3,7,3]]
[[5,3,5],[1,9,5],[3,7,7]]
```
so it would try two 7s before every possible one 7. So we could either just try them all, sort them, and be happy. Or we do something more fancy:
* `∧ℕ≜.` we try a natural number (starting with 0). This will be our output `.`. Also we label it `≜`. So instead of back-unification ("later the square has two 7s, so the output must have been 2"), we already fix the value of the output.
* `{|∧7}ᵐ²` for every value in the square: try it unmodified or replaced by a 7.
* `c{7}ˢl` all digits concatenated, with only the 7s selected, have the length equal to the output.
* `+ᵛS&\+ᵛS` the sum of each row must unify with the sum of each column.
[Answer]
# [R](https://www.r-project.org/), ~~131~~ ~~130~~ ~~118~~ 113 bytes
*Edit: -1 byte thanks to pajonk, and -4 bytes thanks to Giuseppe, which led to another -1 byte too.*
```
function(x,`-`=rowSums,j=expand.grid(rep(list(0:1),9)))min(-j[apply(j,1,function(k)!sd(c(-t(m<-7*k+x*!k),-m))),])
```
[Try it online!](https://tio.run/##jZDBToQwEIbvPgWbvbTr1FBKWTDiS3g0xiULGmDpEsoqPj3O1Gh6gKyZtJnDfP8//wxzV5tXW31Uxubz28Ucx/ps2AQHcciH8@fTpbPQ5NXUF6a8ex/qkg1Vz061HVl4LzlknHOUYKJ5Lvr@9MUakPCn0/KNLdmRiZF1D2K/a2@n3ablIDrE4IV77qwrxqGecDiDGBRWDNSlEHNQnAfbQDwG4c0SodGTCAnURSA9Qi4SCrUT1NZY6AChR0QrHsqpZ6Cdl7pKpDgVovrv83OoRYL2j/CRR0I@HhGv5CBl6RzoBuk/CGJ@klBpj9CLRIT30S517Mr3SFa3wl3cxej3k2fzNw "R – Try It Online")
**How?**  
`j=expand.grid(rep(list(0:1),9))` generates a matrix `j` with 512 rows, corresponding to all possible placements of `7`s in a 9-element matrix.  
We then `apply` the function `!sd(c(-t(m<-7*k+x*!k),-m))` to each row, to determine which ones would yield a semi-magic square if `7`s were placed at those positions in the input matrix `x`.  
From these rows, output the minimum row sum, which was the number of `7`s we needed to place.
(Note that for golfing motives, the short `-` operator is re-assigned to the longer-named `rowSums` function to save bytes, making the code a little difficult to read...)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
JŒPµ³7⁸¦s3§;SEƲµƇḢL
```
[Try it online!](https://tio.run/##y0rNyan8/9/r6KSAQ1sPbTZ/1Ljj0LJi40PLrYNdj206tPVY@8Mdi3z@//8fbaFjBoSGOqY6IJaljmksAA "Jelly – Try It Online")
Takes a flattened list.
Unfortunately, it's not possible to test this with all test cases at once because it uses `³`.
## Explanation
```
JŒPµ³7⁸¦s3§;SEƲµƇḢL   Main monadic link
J                     Indices ([1..9])
 ŒP                   Power set, ordered by length
                Ƈ     Filter by
   µ                  (
    ³                   The input
       ¦                At indices
      ⁸                   given by the argument,
     7                    replace the element with a 7
        s3              Split into groups of 3
              Ʋ         (
          §               Sum of each row
           ;              Join with
            S               Sum of rows (i.e. sum of each column)
             E            All equal?
              Ʋ         )
               µ      )
                 Ḣ    First element
                  L   Length
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~157~~ ~~143~~ ~~136~~ ~~134~~ 132 bytes
```
f z=minimum[sum[1|7<-v]|v<-foldr((<*>).(:[(7:)]).(:))[[]]z,e[sum$(v!!).((4-d)*x+).(d*)<$>l|d<-[1,3],x<-l]]
l=[0..2]
e(x:z)=all(x==)z
```
[Try it online!](https://tio.run/##TY7LboMwEEX3fIUjsbCTAfFMCIJ8Qbvq0vICCVBQDYlCQhHi3@mMS1A9Gvvq@szjWvTfldbLUrMpb5uuaV@t7DH9@ZQ5g5qHzKlvunxwnu0vwuWp5KdUKFJCSKnUBBUV2HzY7dDlkVOK/XhAWe5FZl/0XGaO9CFUMGaOVsrSufRcN1BWxcd0EnmhNR/zXExLWzQdy1lb3D8Zv7@eX8/HR8dc1l9vP/jUgtmMSYvhkWeIIMSIgFQCkSIfZAy@8X0gFYC/@iFyR@RiDKTB2/jQkGeITV24@glqD8l3vvtT3wCT@CPVbP2J8g1NGySbTz9/Eyji1Q9wh9jMjEwk//pgtdmKbjNXLb8 "Haskell – Try It Online")
Takes a flat list of nine numbers.
Shortened by 11 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (143 should have been 147).
Shortened additionally by 4 bytes.
### Explanation
```
f z=minimum[sum[1|7<-v]|              -- count 7s for all solutions and take minimum
  v<-foldr((<*>).(:[(7:)]).(:))[[]]z, -- generate squares with all possible substitutions
  e                                   -- all sums must be equal
    [sum$                             -- compute sums of rows and columns
      (v!!).((4-d)*x+).(d*)<$>l|      -- transform [0..2] to index list and apply to v
        d<-[1,3],x<-l]]               -- parameters for index lists
l=[0..2]                              -- abbreviation, used in two places
e(x:z)=all(x==)z                      -- check whether all numbers in list are equal
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~159~~ ~~152~~ 140 bytes
-7 bytes thanks to Donat  
-4 bytes thanks to Donat
```
lambda l:min(i.count(7)for j in range(512)if 2>len({sum((i:=[(7,L)[M<'1']for L,M in zip(l,f'{j:9b}')])[k%7::k//6])for k in[-5,6,21,22,23]}))
```
[Try it online!](https://tio.run/##TZDBbqMwEIbveQr3sLItTVLAQAAtkXpvn8DlYBLYdeMQhN2V2qrPno5tqi6X0e9/vpn5md/c3@skqnm5je3zzahLf1LENBc9Mb07Xl8nx/Z8vC7kheiJLGr6M7AizbgeSXYww8Q@7OuFMd20ku3hkcun3zSlnSce4ckz73pmBkb68dLU/SflHZfnX/umOd/fl10YfcY2uS2ghCyFLINMdJ@c3/Rlvi6O2De78V3aD0Oxs@6kp2ZD8FPQk5bonZ2NdoyS7YFQHh1895cN/5RhioN1anGt7KIbKIzWR3lEOWJXEJisJ3ctOcYV/psX36yAbg8UjkDvWgorGqYtgzpvBmOHiMR2@mAMcYN1lszK2uFE@U3KGnIQHUiBtcaaQwV51/nLk42UBaSrnUKBFf8HpNFO0RZQQ4nPFRTBRhaSaGeBFitVhypQix@7QpkEKoEKa/KzW6CNGyHD52KlS9QrnYfdkUqRSkIVqP@z43CfwAerw5RgF2hneGkRbEwecuffdLkOF@E0sQYT36fVXw "Python 3.8 (pre-release) – Try It Online")
Takes input as a flat list. Solves by brute-forcing each possible set of 7's. When checking the sums of rows/columns, skips the last row.
```
f=lambda l:                     # l is flat list (9 elements)
  min(                          #
    i.count(7)                  # what we're trying to minimize (the number of 7's used)
    for j in range(512)         # 512=2^9
    if 2>len({                  # check if the len of the set of row/column sums is 1 (it's at least 1 for sure)
      sum(                      # get the sum of a row/column
        (i:=[(7,L)[M<'1']       # Choose the original number or 7 based on whether the binary digit is 1
                                #     (the alternative for the digit is ' ' or '0', which are both < '1')
          for L,M in zip(l,     # 
            f'{j:9b}')])        # gets length 9 binary string
        [k%7::k//6])            # Slice the array to get a row or column
      for k in                  #
      [-5,6,21,22,23]}))        # corresponding slices are i[2::-1] i[6::1] i[0::3] i[1::3] i[2::3]
```
[Answer]
# Java, ~~257~~ ~~246~~ ~~210~~ ~~200~~ ~~195~~ ~~190~~ ~~188~~ ~~186~~ 181 bytes
```
a->{int r=9,i=512,j,e,s,k,x,z,b,c=9;for(;i-->0;r=e!=0|r<c?r:c)for(j=s=e=0;j<3;s=j++<1?x:s,e|=x-s)for(k=x=c=0;k<9;z=b>0?7:a[k],x+=k/3==j?z:0,x+=k++%3==j?30*z:0)c+=b=i>>k&1;return r;}
```
*Saved 11 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904).*
*Saved 46 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).*
*Saved 19 bytes thanks to [Donat](https://codegolf.stackexchange.com/users/95987).*
Takes a flat array as input. This method tries all 512 (29) possibilities by using the binary representations of the integers from `0` to `511`. On each iteration, it sets the values at all indexes where `i` has a set bit to `7`. Then, it checks if the current array is valid, in which case the answer is updated.
[Try it online!](https://tio.run/##TZLBbqMwEIbvfQrvYVehDCwE6AbMEPWy0h721L1FORBKKgOFyDYRTcqzp2NvGlUjm5nf34zHI5ryWHrNc3upulIp9vd8xw7jrhMVU7rU9DkO4pm9lqJniyctRf@y2T46RLGGMv1Ri87fj32lxdD7/4Y/vf59jXLy65dabrYF2zO8lF5xFr1mElMQmIRLaKAGBS1McIIdVJjy/SAXXHheEXCJ9TcM3mVerWVWOeakQYU1BrzJI66wcd08XE@ZgvodJ09ZpMUJK0LaPOUn3BXB@ldWbtotTC62PyPEZn3KAhu57ncbR8E9SU7l4g5FUbQ/Qi5rPcqeST5fOLs9Y7PVtdIKzePZOYUYIrIYjLeCeAarJxBaPQTjLSG86hFxD8QlZERDcOMjS6aQ2Lzoqq/ID4j8XJ/1Td0lLcM/mJxbfUOFljYdrG66Ofl/g7Hkqi@ph8TeGVtbfalD2bYrs8czyTOnzcz3WEpmppDZUTjs6U3p@tUfRu0f6OfQXb/Y@@Xh0L09KhrcwmCOQ9nz3Xz5AA)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 23 bytes
```
nW:qB!"G7@(t!hsd~?@svX<
```
[Try it online!](https://tio.run/##y00syfn/Py/cqtBJUcnd3EGjRDGjOKXO3qG4LMLm//9oYwVLBTNrBQsFUwVTEGWiYBALAA) Or [verify all test cases](https://tio.run/##LY7BCsIwEETvfsXWk8ekm9TECBYR/AFBsQQUevCggrSIJ389zm4lMBOGl8k8ruO9XMrzuHptq/l@2S7G6jb03007vE/rkvPu/DmULpIjTsSwmCCBXJ51nuyUWvIJUpNFyhSpSUC8pCDJKMsTFMVYDtIANwIZCklEe1FHdYIo2@DC2quQFVqMKWiqDTIFy6I8QVrjVy8pFste92eN7A3TFDGXfw).
### Explanation
```
n         % Implicit input. Number of elements: gives 9
W         % 2 raised to that
:q        % Range, minus 1 element-wise. Gives the 1×512 vector [0 1 2 ... 511]     
B!        % Binary, transpose. Gives a 9×512 matrix where each colum is the binary
          % expansion of a number in the above vector
"         % For each column, c (9×1 vector of zeros and ones)
  G       %   Push input
  7       %   Push 7
  @       %   Push current c
  (       %   Write 7 in the input at the entries specified by ones in c
  t!h     %   Duplicate, transpose, concatenate horizontally. Gives a 3×6 matrix
  s       %   Sum of each column
  d~      %   Consecutive differences, negate. Gives a 1×5 vector containing zeros
          %   and ones. If all values are one we have found a solution
  ?       %   If all entries are nonzero
    @s    %     Push c, sum. This is the number of sevens that were written
    vX<   %     Concatenate with any previous results and take the minimum
          %   End (implicit)
          % End (implicit)
          % Display (implicit)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
Ｆφ«≔⭆θ⎇＆ιＸ²λ7κη≔⁺⪪η³Ｅ³⭆⪪η³§μκζ≦Σζ¿⁼⌈ζ⌊ζ⊞υ№η7»Ｉ⌊υ
```
[Try it online!](https://tio.run/##VY5LC8IwEITP@isWTxuIoBaR0lMVDx6Egv6BoK1dTFPNwyf@9piID7wNOzvfzKYWetMK6X3VasCKwb3byY2hncKV1aR2S3HAI4d1qZXQV5ySPZMpc7VF4lC051LjiINkjENv0uOwj6pm2RdTSGdwdZBkseaQBDciEw4//p@b24XalhdsXqxIu0Va@Pvscs37RhXg/OiENLgUF2pcg7fIJ/XWjEHhTI2Ow6x16tURVrIQfnSLUG9xJozFT8KFROZ9kgzGwzRNx75/kk8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of 9 digits. Explanation:
```
Ｆφ«
```
Loop over all possible replacements of digits with `7`, and then some.
```
≔⭆θ⎇＆ιＸ²λ7κη
```
Get the next possible replacement of digits with `7`.
```
≔⁺⪪η³Ｅ³⭆⪪η³§μκζ
```
Split into rows and concatenate with the transpose.
```
≦Σζ
```
Sum the rows and columns.
```
¿⁼⌈ζ⌊ζ
```
If they are all the same, then...
```
⊞υ№η7
```
... save the number of `7`s.
```
»Ｉ⌊υ
```
Print the minimum number of `7`s required.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes
```
^
:
+`:(.)
$1:$%'¶$%`7:
%(`:
$`$`
6`...
$&¶
8O$#`.
$.%`
18`.
$*
)`¶
,
G`\b(1+,)\1{5}
%M`7
O`.
¶.
```
[Try it online!](https://tio.run/##PY8xbsMwDEV3XqNSYjeEIFmWI2ku0KnIAWQHbIEOXTIE3YpeywfwxRyaFjJ9Uu9/irx///7cPlfd0PgG6xUynCg3pgXlstLHZVaazhmYZ1CkCAYyxoA6LDPEi3ohro0mcHGrXqElBgjvNH417oTt6P7CP@gPOsOFHctsYF1LSdijn7B41sTaY8R@mqCUgK4Sh4HVYYdOiMeEA79EDEI4gbZmfPUmUc@9FxK5suK1GFnt8x@ejh2/hJoZuPf1n93r2GtFPfc72adtO25bJ8lupONdghC@SO7pnxkr98S6YxTH9AA "Retina 0.8.2 – Try It Online") Takes input as a string of 9 digits, but link includes test suite that splits on newlines and deletes non-digits for convenience. Explanation:
```
^
:
+`:(.)
$1:$%'¶$%`7:
```
Create all possible combinations of replacing a digit with a `7`.
```
%(`
)`
```
Process each combination separately.
```
:
$`$`
```
Triplicate the string of digits.
```
6`...
$&¶
```
Split the first two copies into rows.
```
8O$#`.
$.%`
```
Transpose the first three columns into rows.
```
18`.
$*
```
Take the sum of each column or row.
```
¶
,
```
Concatenate the results.
```
G`\b(1+,)\1{5}
```
Keep only those that are semimagic.
```
%M`7
```
Count the number of `7`s used.
```
O`.
```
Sort by number of `7`s used.
```
¶.
```
Keep only the smallest number of `7`s used.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 23 bytes
```
lhf!t{ssMMCBc:JQT7 3yU9
```
[Test suite](http://pythtemp.herokuapp.com/?code=lhf%21t%7BssMMCBc%3AJQT7+3yU9&test_suite=1&test_suite_input=%5B9%2C4%2C3%2C3%2C4%2C9%2C4%2C8%2C4%5D%0A%5B5%2C1%2C3%2C3%2C1%2C5%2C1%2C2%2C1%5D%0A%5B3%2C9%2C6%2C8%2C5%2C5%2C8%2C4%2C0%5D%0A%5B5%2C3%2C5%2C1%2C9%2C5%2C3%2C3%2C3%5D%0A%5B8%2C3%2C0%2C8%2C0%2C8%2C0%2C8%2C4%5D%0A%5B1%2C5%2C2%2C5%2C9%2C5%2C6%2C5%2C3%5D%0A%5B3%2C0%2C8%2C1%2C8%2C0%2C1%2C3%2C8%5D%0A%5B3%2C3%2C0%2C5%2C1%2C9%2C9%2C9%2C5%5D%0A%5B2%2C4%2C5%2C5%2C3%2C4%2C4%2C4%2C8%5D%0A%5B3%2C0%2C3%2C8%2C3%2C5%2C8%2C3%2C4%5D&debug=0)
Takes input as a flattened list.
Translation of [xigoi](https://codegolf.stackexchange.com/users/98955/xigoi)['s Jelly answer](https://codegolf.stackexchange.com/a/221254/78186).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~200~~ \$\cdots\$ ~~183~~ 181 bytes
```
def f(a,R=range):
 for b,n in sorted((bin(i).count('1'),i)for i in R(512)):
  c=[[a[i],7][n>>i&1]for i in R(9)]
  if len({(sum(c[3*i:3*i+3]),sum(c[i:9:3]))for i in R(3)})<2:return b
```
[Try it online!](https://tio.run/##TZHBboMwDIbvPIVPI9m8qSHQAhp9iF4zDi0Na7QtIEilbYhnZ3FYpcoxcn4@24nT/7hLZ@WynHULLTvioRqO9l3zMoK2G@CEFoyFsRucPjN2MpYZ/tJ0V@tYLGKOhhNmCDqwTCScMqGplDoqU@OuVna/Nw@ivsMKXnvGtPCpLZvYeP1ijZKPpvT@JGuOq2LKovS7@waSz/w1KQftroOF0@L06EaogKkCU5TeUqQox7RGUBmKIAqkKEFBovTE1hOZN8/hZiVlYArMQoYkMffBxjM3DzWpVuKdyC3Ra036LwJHLfNVJHmtSpaRmPiOWWiSBstv6T4pnIG@ac0j/d3rxg@dbrdBEAhJWBIhDStD2CIUPGouuvnQA4Hx2zXZpU2MECIhYx7R@BxqGuCv6VkYGcKtfHguABpiyxwPm34w/nnbeHIzPO9hGmeY/psoXVVjPcd8@QM "Python 3 – Try It Online")
Inputs a flat list of \$9\$ integers and returns the minimum number of elements that must be replaced with \$7\$s so that the sums of the rows and columns of the corresponding \$3\times3\$ matrix are the same.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~126 123~~ 116 bytes
```
->m{(0..510).map{|x|[120,345,678,360,147,258].map{|a|a.digits.sum{|z|x[z]>0?7:m[z]}}.uniq[1]?9:x.digits(2).sum}.min}
```
[Try it online!](https://tio.run/##PZDdasMwDIXv@xS9bEEz/k2cwtIHMb7IGC25cOnWBtLEfvZMUtJxkBGHT0fCv8PXa7l8Lh9tmg9SCKfkUaTuPucxB6UlGOugqj2YSoKyNWjn4wp0uRPf/bV/PsRjSHOe8him2MpzfUrYlCKGW/8TVDw3p3EjD/pIcBGpv5UlhAYsGJQF6jzYCLt9cKDYVUCdBsWuQaZCxqGQBLmxhqkGHM8YdvFekEi9a82lPI1FbEX8lkuEYpL2@s0lf00mOXY17nW8ybL8fwLO8SX02hjff3jfX8IYy/IH "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes
```
q0//.k_/;!Or@@(Equal@@Tr/@Join[w=MapAt[7&,q,#],w]&/@{1,2,3}~Tuples~{k,2}):>k+1
```
[Try it online!](https://tio.run/##RY/LSgMxGIX3fQsRipeDSSYzdWJpiQs3guiiu1IkSKnD9DbTKV2EdOtS8A18wj5C/CeZ4urkz3fOf1mZ5nO@Mk3xYfxi5KvTzy9n7K58Z8OL11rrq6dqb5ZaT2qmnzfFenoYvZjtYzO976PC5QyH0/fXrM@0FUgg3XGy3y7nu6Mtkbjrh3F5K/xbXawbfbMgU89ahZR8sJJUkabIkToHQhlEhwQy0raliEhCYUBfObKAKAN@TsnOrYJKqmVEOT15cHPkpPx/Fk2gDUHpmBpQLc@zoluQmweVVHcoNmw3bZdXIR1QQhtlAdFl4a60TfWc938 "Wolfram Language (Mathematica) – Try It Online")
-30 bytes from @att
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~151~~ ~~148~~ ~~145~~ ~~142~~ 140 bytes
```
a=>{r=9;for(i=512;i--;r=e|r<c?r:c)for(j=e=0;j<3;a.map((z,k)=>x+=(i>>k&1&&++c?7:z)*(!(~~(k/3)-j)+30*!(k%3-j))),j++?e|=x-s:s=x)c=x=0;return r}
```
[Try it online!](https://tio.run/##PZDRboMwDEXf@Qr6sCopoQMCHS01/ZCKB5SFCeigCmxCXddfZ3baTpYj6@b4Ok5TfpeDMvV59Lv@Xc@VC3MJ@Y@BbVb1htWQhFFW@35mQF/NXh3MTnG6aUBDkDV7mZXrz/LM2EW0HPLJA1bnebsMl0vPU4e33YWv2ILdbqx9ldxvuCeD1YK1LxJrzkXjeQd9hckfdgNMXMGEtkaPX6Zzze886mEc4Oi4x62IhcSIBVWpiAuBaiJCq4aCqkiEVpXIbJBJMJAUwYOVltqKxPZIq6ZYBUg98@5LfhEmsRviH75EhJakuelDJf3uTJFYNcK5iZ0U20j/HbDPvoTOuHAKh/6TFnX7yrULc1f13dCf9PrUf7DKXnKeOfMf "JavaScript (Node.js) – Try It Online")
2 byte reduced thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
### Explanation:
```
a=>{r=9;                 // initial value for minimum
for(i=512;i--;           // i is a bitmask for indexes to replace by 7
 r=e|r<c?r:c)            // minimum of valid squares, e is false if valid
  for(j=e=0;j<3;         // for three rows/columns
   a.map((z,k)=>         // body: compute sum(row) + 30*sum(column)
    x+=                  // current partial sum
      (i>>k&1&&++c?7:z)* // number in current cell, maybe replaced by 7
                         // ++c is always true, here only for counting 7s
      (!(~~(k/3)-j)+     // 1 for current row, else 0
       30*!(k%3-j))),    // 30 for current column, else 0
   j++?e|=x-s:s=x)       // compare sums (s is sum in first iteration)
  c=x=0;                 // initialize number of 7s and sums
return r}                // result
```
Note: We compare the sums of rows and columns only separately. But if the sums of all rows are equal and the sums of all columns are equal, they must be all equal to each other. The sum of the sums of all rows equals the sum of the sums of all columns.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 53 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⌊/+/¨7=,¨a/⍨1=≢¨(∪+/,+⌿)¨a←⎕∘{3 3⍴7@(⍸⍵⊤⍨9/2)⊢⍺}¨⍳512
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=AVoApf/ijIovKy/CqDc9LMKoYS/ijagxPeKJosKoKOKIqisvLCvijL8pwqhh4oaQ4o6V4oiYezMgM@KNtDdAKOKNuOKNteKKpOKNqDkvMiniiqLijbp9wqjijbM1MTI&f=AwA&i=TczBDYNAEEPRO43sdWZtI09DdBPqoA5KoZIQKdKOfHv68rE9n/O@RhFg0Rzb8SclkMqZi1C7JTNaBWUJwCIj/Fv7Sk2VdrXqjdKRcCPEe1alRZMSSPYqYMjg@AI&r=tio&l=apl-dyalog&m=tradfn&n=f)
A tradfn submission which takes a flat array as input from STDIN.
loops over 512 combinations and finds the minimum.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü+üF∙░╔┴!╜U╙],wøT╥B╠╓l6â°
```
[Run and debug it](https://staxlang.xyz/#p=812b8146f9b0c9c121bd55d35d2c770054d242ccd66c3683f8&i=%5B9,+4,+3,+3,+4,+9,+4,+8,+4%5D%0A%5B5,+1,+3,+3,+1,+5,+1,+2,+1%5D%0A%5B3,+9,+6,+8,+5,+5,+8,+4,+0%5D%0A%5B5,+3,+5,+1,+9,+5,+3,+3,+3%5D%0A%5B8,+3,+0,+8,+0,+8,+0,+8,+4%5D%0A%5B1,+5,+2,+5,+9,+5,+6,+5,+3%5D%0A%5B3,+0,+8,+1,+8,+0,+1,+3,+8%5D%0A%5B3,+3,+0,+5,+1,+9,+9,+9,+5%5D%0A%5B2,+4,+5,+5,+3,+4,+4,+4,+8%5D%0A%5B3,+0,+3,+8,+3,+5,+8,+3,+4%5D&m=2)
yet another powerset answer
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 152 bytes
```
p=(m,l=0)=>(q=l=>([a,b,c,d,e,f,g,h,i]=m,l)?m.some((v,j)=>q(l-1,m[j]=7)||(m[j]=v,0)):new Set([a+b+c,d+e+f,g+h+i,a+d+g,b+e+h,c+f+i]).size<2)(l)?l:p(m,l+1)
```
[Try it online!](https://tio.run/##TZHbcoIwEIbveQruTCYrBgJWtNirPkEvkRkRI8QJB4WxTmuf3S4Ba2/42f323wMc00vaZmfVdNOq3sv7vYlICTriNFqTU6TxGaewgwz2IOEAORSgkghL6FvptHUpCbnAEatPRE9dKONjEr3Q242YtwtwSpeV/LQ/ZIed2I5hJyYZdmIFU5CyPcthh5kCMnZgKqFOq77kq0cJjtDLpl@HufTeybbL0la2dmRvrTgOwQeRQCxQQ1QfFuAniT1d2xxxAO6IXQhQXfDAHbCLWEAIc0wvIDAYvcAH7Bm3GF2hUYGxeOIFhty4OCxQ@XO2QIwTwcN0MLrnGI9u38weXC66uFGB8T88NO8v6A8LTReDA8QebhoYjJebu/2Hez42F2Y1MR4mHquF1tbpzqok@IkbrToy2VQT6pRpQ7SqpB2t7V4x0WUFmW32s3yg1x6xK6Ur6@8vOIf6/J5inYHfVlZXba2lo@ucoMNptcok4RBSCtc4TKj1Q1f3Xw "JavaScript (Node.js) – Try It Online")
Take input as a flatten array.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 152 bytes
```
f=(a,m)=>[b=0,1].map(d=>a.map((r,i)=>b|=r.map((n,j)=>s+=d?n:a[j][i],s=0)|1<<s))|b&b-1&&a.map(r=>r.map((n,x)=>r[n-7&&(r[x]=7,v=f(a),v>m?0:m=v),x]=n))|m+1
```
*-8 bytes thanks to @Arnauld!*
[Try it online!](https://tio.run/##dZFBk6IwEIXv/ooctiQpWwqMOKITvO1hD7sHj1mqBjFYWBjYBF23Rn@70wZ05rKn5uX197q72GenzOambNqxrrfqdisEzeDARCI3IoAw9Q9ZQ7ciydwHNVCit7kI02kNe9R2JLYrvcjkPpVlClYE7BK@vlrGLpvhZhwOhx1uRPLkzsgZqccvwyE18pyKFziJgmYMTslhFSwO4sQAnzWGHEbhLa@1bUmeWWWJIEb9OZZGUa@wHvONyrbfy0qt/@mcBsxv63VrSr2jzLdNVbbU@62x7T65KrUiIiHvA0K6SFnq5tgCUedG5a3aphh/73qg48RjS@w2qj0aTeSP9a@ffpMZq6gjGZDRk10Orthc1IbQ/6XXRXcF@7KDUfZYtTi46DOXvVVXyq/qHX379t71XAl9fBIhxDOXrIiX18ag8MiCeH9NrXfelb1h1PUmZQxT4ClIjjXGOoU5TNOUjBMSDKSMIOztECKsIUzw5zs7RJtDDDN8nkPkbGQh6OyJo3lPxa5y1PzTnqMMHBXAHGvwOZujjRNhgs9RT89Q9/TUze6oEKnAVY76i92F3y@4Hxa7FGdHaE9w08jZeLm7e/qgZ304d6vx/jD@WC3@AA "JavaScript (Node.js) – Try It Online")
Takes a matrix of numbers.
[Answer]
# [Perl 5](https://www.perl.org/), 138 bytes
```
sub{(sort map{$i=$_;%e=map{//;$c=$x=$k=0;$x+=($i>>$k&1&&++$c?7:$_)*(!(~~($k/3)-$')+30*!($k++%3-$'))for@_;($x,1)}0..2;%e>1?9:$c}0..511)[0]}
```
[Try it online!](https://tio.run/##PZDxasIwEMb/9ymqnF1iM02axlVDqu/himylgnTT0nZQEH317i5147hw9/G778LVZfNlBji5of35vLH22nTB90d9g7ODo52XjprVykLhoHdQOWmhjxyDc5ZBFaowjCIodm9bOPIFm7LHg0G10vwVXnik5WKKbRTNNfX8dG32R8ugF4rf5XIZ44JM7TZbKKg1SvGDzO@D3Xdl27WOTYLDRiRCYySCqlQkuUDVCOVVJaiKhfKqRmaNjMFAUsgnqz21EcbPaK@mWEmk/nL0Jb8Yk9g18U9fIpQnaW/6VEkfnSmMV2Pca/ymxEf674Bz/if0JvmE20ndnC8dC@HE9ng@EczeLzMe4JWC8QB2@AU "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 73 bytes
```
lMin[Pick[#~t~2,t[w=l+7#-l#]⋃t/@w,{_}]&/@{0,1}~Tuples~{3,3}]
t=Total
```
[Try it online!](https://tio.run/##RU9BasMwELz7G4LQ0i2RLCuVKAZfeiwEmpsxRZiEmCpOaVVyENKlx976g36tH@gT1M3GIaeRdmZ2ZnfWb9c764fe5k2d3d/3z@Mwtsuhf2lZ8qkE3x5qd3PHbh3rfr8@/bw5QHiO3WzeBA4iptXHq1u/pyBBxq7w9WrvrctXy7dhRDG7f@i3@2bTsOtZeurtmEIRgoEK1YCeCgxiBRqqGAEpBWKiBChEASWmECXBwAJHGhRR6AF@dslJbQixDG4hSuOTk5qDRuSXLEyAEkdqci3wL89ZJ7VANSeU@J@o08Jj02N5Q26iSmykiMLL6K7q4uJ0l56aapLEIub8Dw "Wolfram Language (Mathematica) – Try It Online")
Input a 3x3 matrix.
[Answer]
# [Haskell](https://www.haskell.org/), ~~100~~ 95 bytes
* -5 bytes thanks to [Donat](https://codegolf.stackexchange.com/users/95987/donat).
```
f m=minimum[sum[1|7<-n]|n<-g m,a$sum.(g n!!)<$>[7,56,73,146,448]]
g=mapM(:[7])
a(x:y)=all(==x)y
```
[Try it online!](https://tio.run/##TVBBasMwELz7FUrIQQbFxFacOMFqTz32BUIUEWzX1FJD5EACufcRfUOvpffS5lmusotMYbXMamZ2V3rW7qXqumGoiRGmta05Gun8SS/rcm7VxZbzhhimZ/4yoQ2xk0mc1IdX82CPppzdTe@/338@fj@vb9evqYoaYfT@kW7lWsWRpqftORa666gQp/g89JXrd9pVTki5YWTJCIfwAMvCZ8VkzkgaOA@wzHz2HAftCrQ5RAHWBfp4kG8AYA/uuQLQAuT/820ezsggo2@FbpyHwjSYcLUCOaTHkRi55zLYKg9bLEMUY08ODXl4w02kVGR0a@ETn@j@0No@qePx24Y/ "Haskell – Try It Online")
The relevant function is `f`, which takes the flattened matrix `m` as input as list of `Int`'s.
## How?
The real star of this answer is `g=mapM(:[7])`. What is this Haskell magic? Let's start by describing what `mapM` does. `mapM` takes as input a function `f::a->[b]` and a list `l::[a]`, applies `f` to every element of `l` (thus obtaining a list of lists `::[[b]]`), and then returns the cartesian product of these lists. To get a better intuition, consider what happens when we call `mapM(:[7])[2,3,4]`. First we apply `(:[7])` to each element of `[2,3]`, getting `[[2,7],[3,7],[4,7]]` as a result; then we take the cartesian product, resulting in
```
[[2,3,4],[2,3,7],[2,7,4],[2,7,7],[7,3,4],[7,3,7],[7,7,4],[7,7,7]]
```
It should be clear from this example that the function `g`, applied to a list `l`, returns all the lists that can be obtained from `l` by replacing some elements with a `7`. Unsurprisingly, this is exactly what we need for the first step of the solution (i.e. applying `g` to the flattened input matrix `m`); however, a bit more surprisingly, the function `g` will also come in handy later.
---
Now that we know how to *summon the sevens*, we need a way to check if the rows and columns of a given matrix all have the same sum. Dealing with row/column sums in a flattened matrix can be surprisingly cumbersome in Haskell, so we'll have to be somewhat creative. The relevant piece of code is
```
a$sum.(g n!!)<$>[7,56,73,146,448]
```
`a` is simply a function to check whether all the elements of a list are the same (defined later as `a(x:y)=all(==x)y`, not particularly exciting). The interesting part of the code is
```
a$sum.(g n!!)<$>[7,56,73,146,448]
```
, which is basically finding the sum of some specific lists in `g n` (namely, the one in position `7`, the one in position `56` and so on). What's so special about these positions? Assuming `n≡[n0,n1,...,n7,n8]`, the `7`-th element of `g n` is `[n0,n1,n2,n3,n4,n5,7,7,7]`. Similarly, here is a list of the elements of `g n` we are considering.
| `i` | `i`-th element of `g n` |
| --- | --- |
| `7` | `[n0,n1,n2,n3,n4,n5,7 ,7 ,7 ]` |
| `56` | `[n0,n1,n2,7 ,7 ,7 ,n6,n7,n8]` |
| `73` | `[n0,n1,7 ,n3,n4,7 ,n6,n7,7 ]` |
| `146` | `[n0,7 ,n2,n3,7 ,n5,n6,7 ,n8]` |
| `448` | `[7 ,7 ,7 ,n3,n4,n5,n6,n7,n8]` |
With some algebra, it's easy to see that the sums of these five lists are all equal if and only if the sums of all the rows and columns of `n` are equal.
---
Sorry, the clever part is over, the definition of `f` is moderately boring.
```
f m=                                    -- f is a function that takes a flattened matrix m
    minimum[                            -- and returns the minimum of
    sum[1|7<-n]|                        -- the numbers of 7's in n (sum 1 for each 7 in n), where
    n<-g m,                             -- n is an element of g m
    a$sum.(g n!!).fromEnum<$>"?ÛŭƶǇǸ"]  -- all the sums of rows and columns of n are equal
```
To compensate, here is a fun fact: most of the other solutions posted here have a time complexity of \$O(2^{n^2})\$ (up to a polynomial in \$n\$), while this answer runs in \$O(4^{n^2})\$, where \$n\$ is the number of rows/columns of the input matrix.
]