Archive for the ‘CFKrypton’ Category

Find the closest in a list of numbers

Saturday, April 26th, 2014

For a while now I’ve been working on a core set of functionality that I include with every application. In fact, my applications extend a core app that contains a whole bunch of commonly used functionality – but that’s a whole other post.

I’d intended to blog about some of the components I’ve been writing as I go along, but as is so often the case I find myself moving onto new work before I’ve sat down to write about the last.

Today, I needed to pass a number to a function and return the closest number in a given list.
So for example, a list of ‘10,20,50,100,200,1000’ and a value of 42, should return 50.

It’s a simple requirement, but Google returned nothing & the mighty Ben Nadel hadn’t written a comprehensive post on how to do it along with speed tests and examples involving hot girls; so I wrote a function and added it to my ever increasing library.

As it’s small, I thought I’d share… in doing so, I realised I’ve not updated this site in way too long – so for this I apologise.

Here’s what I came up with – hopefully it’ll save someone a bit of time:

<cffunction name="closestNumberInList" returntype="numeric" hint="Returns the closest number in a list to the given value">
<cfargument name="Value" type="numeric" required="true" hint="A number to convert to the nearest in our list">
<cfargument name="List" type="string" required="true" hint="A list of valid numbers we can return">
<cfscript>
var Local = {};
// Convert list to array
Local.ListArray = ListToArray(Arguments.List);
// Set up variable to hold the lowest difference
Local.LowestDifference = '';
// Loop through array
For (Local.ThisNumber IN Local.ListArray) {
// Calculate difference between this and the value
Local.ThisDifference = abs(Local.ThisNumber - Arguments.Value);
// If the new calculated is lower than the existing, replace it.
if (NOT isNumeric(Local.LowestDifference) OR Local.ThisDifference LT Local.LowestDifference) {
Local.LowestDifference = Local.ThisDifference;
// Set return value
Local.ReturnVal = Local.ThisNumber;
}
}
return Local.ReturnVal;
</cfscript>
</cffunction>

Posted in CFKrypton, ColdFusion, Railo | Comments Off on Find the closest in a list of numbers

About

Simian Enterprises is the trading name of Gary Stanton, a freelance web developer working by the sea in Brighton, UK. Gary's been creating websites since 1996 and still loves it. Read more

Contact

Gary Stanton

Email:

Tel:
01273 775522

Twitter

No public Twitter messages.

Delicious Feed

Website Design & Development