-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path861_ScoreAfterFlippingMatrix.swift
61 lines (57 loc) · 1.5 KB
/
861_ScoreAfterFlippingMatrix.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
func matrixScore(_ A: [[Int]]) -> Int {
var matrix = toggleMatrixRows(A)
matrix = toggleMatrixColumns(matrix)
var total = 0
for row in matrix {
total += valueFromArray(row)
}
return total
}
func toggleMatrixRows(_ A: [[Int]]) -> [[Int]] {
var matrix = A
for i in 0..<A.count {
if A[i][0] == 0 {
matrix[i] = toggledArray(A[i])
}
}
return matrix
}
func toggleMatrixColumns(_ A: [[Int]]) -> [[Int]] {
var matrix = A
let rows = A.count
let cols = A[0].count
for i in 1..<cols {
var countOne = 0
var countZero = 0
for j in 0..<rows {
if A[j][i] == 1 {
countOne += 1
} else {
countZero += 1
}
}
if countOne < countZero {
for j in 0..<rows {
matrix[j][i] = matrix[j][i] ^ 1
}
}
}
return matrix
}
func toggledArray(_ arr: [Int]) -> [Int] {
var toggledArray = [Int]()
for i in arr {
toggledArray.append( i ^ 1)
}
return toggledArray
}
func valueFromArray(_ arr:[Int]) -> Int {
var str = ""
for i in arr {
str = str + String(i)
}
let value = Int(str, radix:2)
return value!
}
}