Skip to content

Commit 0860783

Browse files
committed
Backup files
1 parent bb3cdc2 commit 0860783

File tree

4 files changed

+69
-1
lines changed

4 files changed

+69
-1
lines changed

problems/nth_root.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Calculate nth root (within givin tolerance) without standard library
2+
# for embedded system with little space
3+
4+
# Root must be between 0 and number
5+
# Binary search of possibilites from 0 to number
6+
7+
# Set left and right boundaries
8+
# While left is less than right
9+
# Check if midpoint ^ n is within tolerance of number
10+
# If value is too big
11+
# Set right to midpoint
12+
# Else
13+
# Set left to midpoint
14+
# Update midpoint to new average of left and right
15+
# Return midpoint
16+
17+
def nth_root(number, n, tolerance = 0.001)
18+
low = 0
19+
high = number
20+
loop do
21+
midpoint = (low + high) / 2.0
22+
error = midpoint**n - number
23+
return midpoint if error.abs < tolerance
24+
if error > 0
25+
high = midpoint
26+
else
27+
low = midpoint
28+
end
29+
end
30+
end
31+
32+
# Time complexity: O(log(n))
33+
# Space complexity: O(1)

problems/num_of_paths_to_dest.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def num_of_paths_to_dest(size)
2+
memo = Array.new(size, [])
3+
num_of_paths_to_sq(size - 1, size - 1, memo)
4+
end
5+
6+
def num_of_paths_to_sq(x, y, memo)
7+
if x < 0 || y < 0
8+
return 0
9+
elsif x < y
10+
memo[x, y] = 0
11+
elsif x == 0 && y == 0
12+
memo[x, y] = 1
13+
elsif memo[x, y].nil?
14+
memo[x, y] = num_of_paths_to_sq(x - 1, y, memo) + num_of_paths_to_sq(x, y - 1, memo)
15+
end
16+
17+
memo[x, y]
18+
end
19+
20+
puts num_of_paths_to_dest(4)

sorts/insertion_sort.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
def insertion_sort(arr)
1515
arr.each_with_index do |num, index|
16-
prev_index = index - 1
16+
prev_index = index - 1 # Check index -1 edge case
1717
while prev_index >= 0 && arr[prev_index] > num
1818
arr[prev_index + 1] = arr[prev_index]
1919
prev_index -= 1

spec/nth_root_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
require_relative '../problems/nth_root'
2+
3+
RSpec.describe 'nth root' do
4+
it 'takes nth root of a number' do
5+
number = 7
6+
n = 3
7+
expect((nth_root(number, n)**n - number).abs <= 0.001).to eq(true)
8+
end
9+
10+
it 'takes nth root of a number' do
11+
number = 4
12+
n = 2
13+
expect((nth_root(number, n)**n - number).abs <= 0.001).to eq(true)
14+
end
15+
end

0 commit comments

Comments
 (0)