Skip to content

Commit 3415326

Browse files
author
Mauricio Klein
committed
Rewrite challenge #1 in Python + code optimizations
1 parent 8d8292b commit 3415326

File tree

9 files changed

+73
-164
lines changed

9 files changed

+73
-164
lines changed

challenge-1/Gemfile

-4
This file was deleted.

challenge-1/Gemfile.lock

-26
This file was deleted.

challenge-1/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-1/__init__.py

Whitespace-only changes.

challenge-1/lib/solver.rb

-72
This file was deleted.

challenge-1/solver.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
RIGHT = 1
2+
DOWN = 2
3+
LEFT = 3
4+
UP = 4
5+
6+
#
7+
# Time complexity: O(n*m)
8+
# Space complexity: O(n*m) (result array)
9+
#
10+
def spiral_traverse(arr, n_rows, m_columns):
11+
def inbounds(row, column):
12+
return (0 <= row < n_rows) and (0 <= column < m_columns)
13+
14+
matrix = to_matrix(arr, n_rows, m_columns)
15+
result = []
16+
17+
row, column, direction = 0, 0, RIGHT
18+
19+
for _ in range(n_rows * m_columns):
20+
# Visit the cell
21+
result.append(matrix[row][column])
22+
matrix[row][column] = None
23+
24+
# Check if we need to change directions
25+
nr, nc = next_step(direction, row, column)
26+
if not inbounds(nr, nc) or matrix[nr][nc] == None:
27+
direction = next_direction(direction)
28+
29+
row, column = next_step(direction, row, column)
30+
31+
return result
32+
33+
def next_step(direction, row, column):
34+
return {
35+
RIGHT: (row , column + 1),
36+
DOWN : (row + 1, column ),
37+
LEFT : (row , column - 1),
38+
UP : (row - 1, column )
39+
}[direction]
40+
41+
def next_direction(current_direction):
42+
return {
43+
RIGHT: DOWN,
44+
DOWN : LEFT,
45+
LEFT : UP,
46+
UP : RIGHT
47+
}[current_direction]
48+
49+
def to_matrix(arr, rows, columns):
50+
matrix = [ [ 0 for i in range(columns) ] for j in range(rows) ]
51+
52+
for i in range(columns):
53+
for j in range(rows):
54+
matrix[i][j] = arr[i * rows + j]
55+
56+
return matrix

challenge-1/spec/solver_spec.rb

-61
This file was deleted.

challenge-1/spec/spec_helper.rb

-1
This file was deleted.

challenge-1/test_solver.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import unittest
2+
from solver import spiral_traverse
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_spiral_traverse(self):
6+
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
7+
expected = [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
8+
rows, columns = 4, 4
9+
10+
self.assertEqual(spiral_traverse(arr, rows, columns), expected)
11+
12+
if __name__ == "__main__":
13+
unittest.main()

0 commit comments

Comments
 (0)