dmatthews
asked on
How to search a list in coldfusion for a value that is less than a predifined value
I have a situation where I have a list with 50 numbers of values which increment by 10000. What I want to do is find a value in that list that is less than a predifined variable. FOR EXAMPLE:
VARIABLE X = 128,000
I want to search that list so that it will find the max value that is less than $128,000. Which in the case of the list I have will be $120,000.
Anybody have any suggestions on how to do this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
BUt will that get the max value. IE. There is a list with 10 value. 10,000 -100,000. The value for x is 85,000. Going through the list the first value of 10,000 will work that that is what y will be set to when i really want y to be 80,000.
orangachang's code will work, but here is a slight improvement for you that doesn't loop through every record if it doesn't have to, and also makes sure the list is sorted properly first...
<CFSET MyList = "20000,30000,10000,40000,5 0000">
<CFSET MyListArray = listtoarray(Mylist)>
<CFSET sortlist = arraysort(MyListArray,"num eric")>
<CFSET MyList = arraytolist(MyListArray)>
<cfset x = 28000>
<cfset y = 0>
<cfloop from="1" to="#ListLen(MyList)#" index="i">
<cfif ListGetAt(MyList,i) gt x>
<cfset y = i-1>
<CFBREAK>
</cfif>
</cfloop>
<CFIF y lte 0>
no value lower found
<CFELSE>
<cfoutput>#ListGetAt(MyLis t,y)#</cfo utput>
</cfif>
<CFSET MyList = "20000,30000,10000,40000,5
<CFSET MyListArray = listtoarray(Mylist)>
<CFSET sortlist = arraysort(MyListArray,"num
<CFSET MyList = arraytolist(MyListArray)>
<cfset x = 28000>
<cfset y = 0>
<cfloop from="1" to="#ListLen(MyList)#" index="i">
<cfif ListGetAt(MyList,i) gt x>
<cfset y = i-1>
<CFBREAK>
</cfif>
</cfloop>
<CFIF y lte 0>
no value lower found
<CFELSE>
<cfoutput>#ListGetAt(MyLis
</cfif>
ASKER
YOur code works however I found that if I tried to continuously update x inside the loop it wouldnt finish going through the values. I had the following
<cfoutput>
<cfset x = 128000>
<cfset y = 0>
<cfloop index="i" from="1" to="#ListLen(MyList)#">
<cfif ListGetAt(MyList, i) lte x>
<cfset x = i>
</cfif>
</cfloop>
<cfoutput>
<cfset x = 128000>
<cfset y = 0>
<cfloop index="i" from="1" to="#ListLen(MyList)#">
<cfif ListGetAt(MyList, i) lte x>
<cfset x = i>
</cfif>
</cfloop>
ASKER