aboutsummaryrefslogtreecommitdiff
path: root/challenge-218/robert-dicicco/ruby/ch-2.rb
blob: 976ce5a2787c2b4d562f103245f9eca86efc34ce (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env ruby
#---------------------------------------------
# AUTHOR: Robert DiCicco
# DATE  : 2023-05-27
# Challenge 218 MatrixScore.py ( Ruby )
#---------------------------------------------

$matrix = [ [0,0,1,1],
           [1,0,1,0],
           [1,1,0,0], ]

def GetColVal(c)
    testmat = []
    row = 0
    while row < 3
        testmat.push($matrix[row][c])
        row += 1
    end
    colval = binary_to_decimal(testmat)
    return colval
end

def ToggleCol(c)
    ov = GetColVal(c);
    row = 0
    testmat = []
    testval = 0
    while row < 3
        $matrix[row][c] == 0 ? testmat.push(1) : testmat.push(0)
        row += 1
    end
    testval = binary_to_decimal(testmat);
    if testval > ov
        x = 0
        while x < 3
            $matrix[x][c] = testmat[x]
            x += 1
        end
        puts("Toggled column #{c+1}")
        ShowMatrix()
    end
end

def ToggleRow(r, ov)
    testmat = []
    col = 0
    while col <= 3
        x = $matrix[r][col]
        if x == 0
            testmat.push(1)
        else
            testmat.push(0)
        end
        col += 1
    end
    testval = binary_to_decimal(testmat)
    if testval > ov
        puts("\nToggled row #{r+1}")
        $matrix[r] = testmat
        ShowMatrix()
    end
end

def ShowMatrix()
    total = 0
    cnt = 0
    while cnt < 3
        puts("#{$matrix[cnt]}")
        total += binary_to_decimal($matrix[cnt])
        cnt += 1
    end
    puts("Total = #{total}\n\n")
end

def binary_to_decimal(binary_array)
    decimal = 0
    power = binary_array.length() - 1
    binary_array.each do |digit|
        decimal += digit * ( 2 ** power)
        power -= 1
    end
    return decimal
end

ShowMatrix()
myrow = 0
while myrow < 3
    bd = binary_to_decimal($matrix[myrow].to_a)
    ToggleRow(myrow,bd)
    myrow += 1
end

mycol = 0
while mycol < 4
    ToggleCol(mycol)
    mycol += 1
end

#---------------------------------------------
# SAMPLE OUTPUT
# ruby .\MatrixScore.rb
# [0, 0, 1, 1]
# [1, 0, 1, 0]
# [1, 1, 0, 0]
# Total = 25

# Toggled row 1
# [1, 1, 0, 0]
# [1, 0, 1, 0]
# [1, 1, 0, 0]
# Total = 34

# Toggled column 3
# [1, 1, 1, 0]
# [1, 0, 0, 0]
# [1, 1, 1, 0]
# Total = 36

# Toggled column 4
# [1, 1, 1, 1]
# [1, 0, 0, 1]
# [1, 1, 1, 1]
# Total = 39
#---------------------------------------------