Introduction
Provided are some toy implementations for some basic computer science problems.
Tree data structures
Node- references children nodes onlyChildNode- references parent and children nodesTree- tracks therootnode; providesdf_searchandbf_searchNaryTree- enforces number of children per node viachild_slotsBinaryTree-NaryTreewithchild_slots== 2; providesto_sCompleteBinaryTree- efficient Array implementation
Heap data structure
Implemented with a CompleteBinaryTree for storage using simple arithmetic to
determine array indices for parent and children. See the
heap example which can be executed (among other examples)
via rake examples.
Both minheaps and maxheaps are supported. The primary operations are
Heap#push and Heap#pop. My basic Vagrant VM gets around 500k pushes per
second, constant up past 1M pushes.
Fibonacci functions
Fibonacci.classic(n)- naive, recursiveFibonacci.cache_recursive(n)- as above, caching already computed resultsFibonacci.cache_iterative(n)- as above but iterativeFibonacci.dynamic(n)- as above but without a cache structureFibonacci.matrix(n)- matrix is magic; beats dynamic around n=500
Timer functions
Timer.now- usesProcess::CLOCK_MONOTONICif availableTimer.since- provides the elapsed time since a prior timeTimer.elapsed- provides the elapsed time to run a blockTimer.loop_avg- loops a block; returns final value and mean elapsed time
require 'compsci/timer'
include CompSci
overall_start = Timer.now
start = Timer.now
print "running sleep 0.01 (50x): "
_answer, each_et = Timer.loop_avg(count: 50) {
print '.'
sleep 0.01
}
puts
puts "each: %0.3f" % each_et
puts "elapsed: %0.3f" % Timer.since(start)
puts "cumulative: %0.3f" % Timer.since(overall_start)
puts
start = Timer.now
print "running sleep 0.02 (0.3 s): "
_answer, each_et = Timer.loop_avg(seconds: 0.3) {
print '.'
sleep 0.02
}
puts
puts "each: %0.3f" % each_et
puts "elapsed: %0.3f" % Timer.since(start)
puts "cumulative: %0.3f" % Timer.since(overall_start)
puts
running sleep 0.01 (50x): ..................................................
each: 0.010
elapsed: 0.524
cumulative: 0.524
running sleep 0.02 (0.3 s): ...............
each: 0.020
elapsed: 0.304
cumulative: 0.828
Fit functions
Fit.sigma- sums the result of a block applied to array valuesFit.error- returns a generic r^2 value, the coefficient of determinationFit.constant- fitsy = a + 0x; returns the mean and varianceFit.logarithmic- fitsy = a + b*ln(x); returns a, b, r^2Fit.linear- fitsy = a + bx; returns a, b, r^2Fit.exponentialfitsy = ae^(bx); returns a, b, r^2Fit.powerfitsy = ax^b; returns a, b, r^2