Skip to content

Instantly share code, notes, and snippets.

View bgmarx's full-sized avatar

Ben Marx bgmarx

View GitHub Profile
@bgmarx
bgmarx / halve array
Last active August 29, 2015 14:00
Divide an array into two equal parts
def halve_array(arr)
median = (arr.size / 2).round
[arr.take(median), arr.drop(median)]
end
# a=*(1..100)
# b = halve_array(a)
# => [[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]]
# b[0] = => [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]
# b[1] = => [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]
@bgmarx
bgmarx / merge sort
Last active August 29, 2015 14:00
Merge Sort
def merge_sort(arr)
return arr if arr.size <= 1
left, right = halve_array(arr)
left_part = merge_sort(left)
right_part = merge_sort(right)
array = []
offset_left_part = 0
offset_right_part = 0
@bgmarx
bgmarx / chessboard
Created May 2, 2014 03:48
make a chessboard
def chess_board(size = 8)
i = 0
j = 0
while i < (size * size)
if i % (size) == 0
puts ""
j % 2 == 0 ? print("# " * (size / 2)) : print(" #" * (size / 2))
j += 1
end
i += 1
@bgmarx
bgmarx / bubble-sort
Created May 3, 2014 03:32
bubble sort
def bubble_sort(list)
return list if list.size <= 1
swapped = true
while swapped
swapped = false
0.upto(list.size-2) do |i|
if(list[i] > list[i+1])
list[i + 1], list[i] = list[i], list[i+1]
swapped = true
end
(defn halve [a-seq]
(let [half (int (/ (count a-seq))) 2]
(vector (my-take half a-seq) (my-drop half a-seq))))
(defn my-take [n coll]
(if (or (empty? coll)
(zero? n))
'()
(cons (first coll) (my-take (dec n) (rest coll)))))
(defn my-drop [n coll]
(if (or (empty? coll)
(zero? n))
coll
(my-drop (dec n) (rest coll))))
(defn seq-merge [a-seq b-seq]
(cond (empty? a-seq) b-seq
(empty? b-seq) a-seq
(> (first a-seq) (first b-seq))
(cons (first b-seq) (seq-merge a-seq (rest b-seq)))
:else (cons (first a-seq) (seq-merge b-seq (rest a-seq)))))
(defn merge-sort [a-seq]
(cond (empty? a-seq) a-seq
(singleton? a-seq) a-seq
:else (let [[a b] (halve a-seq)]
(seq-merge (merge-sort a)
(merge-sort b)))))
(defn singleton [coll]
(and (not (empty? coll)) (empty? (rest coll))))