//Title: Nearest Value in List Snippet
//Credit to: Jtgibson
//Contributed by: Jtgibson
//This snippet takes a number and finds the value in the
// list that is closest to it.
//Note: in cases where a number is exactly between two entries, the
// last entry is the one returned as closer.
proc/near(num, list/L)
if(!num || !L || !L.len) return null
var/closest = null
for(var/i = 1, i <= L.len, i++)
ASSERT(isnum(L[i]))
if(closest == null || ((abs(L[i] - num) + 1) <= (abs(closest - num) + 1)))
closest = L[i]
return closest
///*
//Testing code/sample implementation:
mob/verb/test_near()
var/list/numbers = list(1,2,5,10,20,25,30,40,50,60,70,75,80,85,90,100)
usr << "Nearest to 7: [near(7, numbers)]"
usr << "Nearest to 39: [near(39, numbers)]"
usr << "Nearest to 88: [near(88, numbers)]"
usr << "Nearest to 74: [near(74, numbers)]"
usr << "Nearest to 95: [near(95, numbers)]"
//*/
ID:195148
Nov 21 2006, 6:59 am
|
|