Part 1
Description
Solution
For this problem, at first I thought of making a grid of 1000*1000 cells, marked with coordinates of (0,0) through (999,999). But, then it will be long to make a calculation in such vast area. So, I decided to use VBA, reading the input, and constructing the grid in a two dimensional array. Here is the split input in Excel.And, the code:
Sub Hazard3() Dim c, x0, y0, x1, y1, x2, y2, rows As Integer Dim map(0 To 999, 0 To 999) As Variant Dim action As String ActiveSheet.Range("h3").Select x0 = 11 y0 = 11 Start: ActiveCell.Offset(1, 0).Select rows = ActiveCell.Row x1 = Cells(rows, 3).Value y1 = Cells(rows, 4).Value x2 = Cells(rows, 6).Value y2 = Cells(rows, 7).Value action = Cells(rows, 2).Value If IsEmpty(Cells(rows, 3)) Then GoTo Finish Else If action = "turnon" Then For c = x1 To x2 For d = y1 To y2 map(c, d) = 1 Next d Next c ElseIf action = "turnoff" Then For c = x1 To x2 For d = y1 To y2 map(c, d) = 0 Next d Next c Else For c = x1 To x2 For d = y1 To y2 map(c, d) = (map(c, d) + 1) Mod 2 Next d Next c End If End If ActiveSheet.Cells(rows, 7).Select GoTo Start Finish: ActiveSheet.Cells(3, 10).Select ActiveCell.Value = Application.WorksheetFunction.Sum(map) End Sub
This code basically modify the value of corresponding array (map) according to the input value and the instruction (toggle, turn on or turn off) and finally sum up the array.
Part 2
Description
Solution
For the part 2, only the instruction is changed. So, I modified the code into this:
Sub Hazard2() Dim c, x0, y0, x1, y1, x2, y2, rows As Integer Dim map(0 To 999, 0 To 999) As Variant Dim action As String ActiveSheet.Range("h3").Select x0 = 11 y0 = 11 Start: ActiveCell.Offset(1, 0).Select rows = ActiveCell.Row x1 = Cells(rows, 3).Value y1 = Cells(rows, 4).Value x2 = Cells(rows, 6).Value y2 = Cells(rows, 7).Value action = Cells(rows, 2).Value If IsEmpty(Cells(rows, 3)) Then GoTo Finish Else If action = "turnon" Then For c = x1 To x2 For d = y1 To y2 map(c, d) = map(c, d) + 1 Next d Next c ElseIf action = "turnoff" Then For c = x1 To x2 For d = y1 To y2 If map(c, d) > 0 Then map(c, d) = map(c, d) - 1 End If Next d Next c Else For c = x1 To x2 For d = y1 To y2 map(c, d) = map(c, d) + 2 Next d Next c End If End If ActiveSheet.Cells(rows, 7).Select GoTo Start Finish: ActiveSheet.Cells(5, 10).Select ActiveCell.Value = Application.WorksheetFunction.Sum(map) End Sub
0 komentar:
Post a Comment