Skip to content

Commit f1291ff

Browse files
committed
Added ruby array manipulation category and some snippets
1 parent 85ff2d8 commit f1291ff

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
title: Binary Search
3+
description: Searches for an element in a sorted array using binary search.
4+
author: ACR1209
5+
tags: ruby,array,binary-search,search
6+
---
7+
8+
```rb
9+
def binary_search(array, target)
10+
low = 0
11+
high = array.length - 1
12+
13+
while low <= high
14+
mid = (low + high) / 2
15+
guess = array[mid]
16+
17+
if guess == target
18+
return mid
19+
elsif guess > target
20+
high = mid - 1
21+
else
22+
low = mid + 1
23+
end
24+
end
25+
26+
return nil
27+
end
28+
29+
# Usage
30+
array = [1, 3, 5, 7, 9]
31+
target = 5
32+
result = binary_search(array, target)
33+
puts result # Output: 2
34+
```
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
title: Chunk Array
3+
description: Splits an array into chunks of a specified size.
4+
author: ACR1209
5+
tags: ruby,array,chunk,utility
6+
---
7+
8+
```rb
9+
def chunk_array(array, size)
10+
array.each_slice(size).to_a
11+
end
12+
13+
# Example usage:
14+
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
15+
chunked_arr = chunk_array(arr, 2)
16+
puts chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
17+
```
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
title: Matrix Transpose
3+
description: Transposes a 2D matrix.
4+
author: ACR1209
5+
tags: ruby,array,matrix,transpose
6+
---
7+
8+
```ruby
9+
def transpose_matrix(matrix)
10+
return [] if matrix.empty?
11+
return [] if matrix.first.empty?
12+
13+
matrix.first.zip(*matrix[1..-1])
14+
end
15+
16+
# Usage
17+
matrix = [
18+
[1, 2, 3],
19+
[4, 5, 6],
20+
[7, 8, 9]
21+
]
22+
print transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
23+
```

0 commit comments

Comments
 (0)