Last active
June 19, 2018 16:10
-
-
Save kulicuu/702d2856f1e1ac5c1dd711053760830d to your computer and use it in GitHub Desktop.
Search sorted, pivoted array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
c = console.log.bind console | |
color = require 'bash-color' | |
_ = require 'lodash' | |
fp = require 'lodash/fp' | |
# this one gives the array above the pivot, inclusive of the pivot. | |
upper_rayy_incl = (rayy, pivot) -> | |
[].concat rayy.slice(pivot) | |
# this one gives the array above the pivot, non-inclusive | |
upper_rayy = (rayy, pivot) -> | |
[].concat rayy.slice(pivot + 1) | |
# this one gives the array below the pivot, non-inclusive | |
lower_rayy = (rayy, pivot) -> | |
[].concat rayy.slice(0, pivot) | |
find_pivot = (rayy) -> | |
pivot = -1 | |
for item, idx in rayy | |
if item.val > rayy[idx + 1].val | |
pivot = idx + 1 | |
break | |
return pivot | |
binary_search = (rayy, target) -> | |
midpoint_idx = Math.floor(rayy.length / 2) | |
val_at_midpoint = rayy[midpoint_idx] | |
unless val_at_midpoint is undefined | |
if val_at_midpoint.val > target | |
arguments.callee(lower_rayy(rayy, midpoint_idx), target) | |
else if val_at_midpoint.val < target | |
arguments.callee(upper_rayy(rayy, midpoint_idx), target) | |
else if val_at_midpoint.val is target | |
return val_at_midpoint.idx | |
exports.default = f2 = (rayy, target) -> | |
pivot = find_pivot rayy | |
if pivot is target | |
return pivot | |
else | |
up_rayy = upper_rayy_incl(rayy, pivot) | |
if target <= up_rayy[up_rayy.length - 1].val | |
return binary_search up_rayy, target | |
else | |
c 'nought' | |
low_rayy = lower_rayy(rayy, pivot) | |
# c low_rayy | |
return binary_search(low_rayy, target) | |
rayy = [59, 68, 77, 83, 123, 144, 8, 13, 38, 42] | |
rayy_x = _.map rayy, (val, idx) -> | |
{ val, idx } | |
for target, idx in rayy | |
answer = f2 rayy_x, target | |
c (color.cyan 'final', on),(color.white answer, on) | |
# TEST | |
if rayy[answer] isnt target | |
c color.red "ERROR...", on | |
else | |
c color.green "GOOD ANSWER...", on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment