Skip to content

Commit 7a475c9

Browse files
committed
Add utils to parse 2D array
1 parent d8d6311 commit 7a475c9

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

2024/ruby/.rubocop.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,9 @@ Style/Documentation:
1616

1717
Style/MultilineBlockChain:
1818
Enabled: false
19+
20+
Naming/MethodParameterName:
21+
Enabled: false
22+
23+
Minitest/MultipleAssertions:
24+
Enabled: false

2024/ruby/lib/util.rb

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# frozen_string_literal: true
2+
3+
module Util
4+
Point2D = Data.define(:x, :y)
5+
6+
class Array2D
7+
def initialize(n_rows, n_cols)
8+
@n_rows = n_rows
9+
@n_cols = n_cols
10+
@data = Array.new(n_rows * n_cols)
11+
end
12+
13+
def [](p)
14+
if p.instance_of? Point2D
15+
row_idx = p.y
16+
col_idx = p.x
17+
else
18+
row_idx, col_idx = p
19+
end
20+
21+
raise IndexError if row_idx.negative? || row_idx >= @n_rows || col_idx.negative? || col_idx >= @n_cols
22+
23+
@data[(row_idx * @n_cols) + col_idx]
24+
end
25+
26+
def []=(p, value)
27+
if p.instance_of? Point2D
28+
row_idx = p.y
29+
col_idx = p.x
30+
else
31+
row_idx, col_idx = p
32+
end
33+
34+
raise IndexError if row_idx.negative? || row_idx >= @n_rows || col_idx.negative? || col_idx >= @n_cols
35+
36+
@data[(row_idx * @n_cols) + col_idx] = value
37+
end
38+
39+
def self.parse(s)
40+
a = Array2D.new(
41+
s.split.length,
42+
s.split[0].length
43+
)
44+
s.split.each_with_index do |row, row_idx|
45+
row.chars.each_with_index do |char, col_idx|
46+
a[[row_idx, col_idx]] = char
47+
end
48+
end
49+
a
50+
end
51+
end
52+
end

2024/ruby/test/util_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
require 'minitest/autorun'
4+
require_relative '../lib/util'
5+
6+
module UtilTest
7+
class Array2DTest < Minitest::Test
8+
def test_parse
9+
s = "ABC
10+
DEF"
11+
12+
a = Util::Array2D.parse(s)
13+
14+
assert_equal 'A', a[[0, 0]]
15+
assert_equal 'B', a[[0, 1]]
16+
assert_equal 'C', a[[0, 2]]
17+
assert_equal 'D', a[[1, 0]]
18+
assert_equal 'E', a[[1, 1]]
19+
assert_equal 'F', a[[1, 2]]
20+
end
21+
end
22+
end

0 commit comments

Comments
 (0)