Cool Code Using VFP 9 (by John Koziol)


(UPDATED) … Whoops, wrong alias name used in the USE IN command.  Repaired now <g>


So Richard Stanton, part of the VFP Dev team and the author of all the great VFP Report enhancements in VFP 9, and I were going over a very cool algorithm.  I can’t get into what it does as we haven’t decided what to do with it, but it’s slick. 


You know what I mean by slick, right? In my experience, developers will ooh-and-ahh at great algorithms regardless of how useful they are.  If the code is elegant we get a warm-and-fuzzy feeling. I have a pet theory that this asthetic appreciation gets developers into trouble sometime – we love th code so much we refuse to see it may not be the right solution.


So Richard mentioned an old project of his to convert Arabic numbers (our standard numbers) into Roman numbers.  I thought about it, and replied that I thought I could do it in 30 lines of code or less, not including any setup code like asking for the number or creating data structures that can be re-used. He sort of challenged me on that, and here’s the result.  Kinda cool but with very little real-world usefulness (heh).  Sorry about the formatting.


 


 


* Arabic to Roman … John Koziol May 10, 2005


* Public domain:  Share and enjoy.


cNum=INPUTBOX(“Enter a number between 1 and 3999″,”Enter number”)


nVal=VAL(cNum)


IF !BETWEEN(nVal,1,3999)


=MESSAGEBOX(“Can’t even follow simple instructions?, Well begone!”,”Input Issue”,16)


RETURN


ENDIF


 


DO MakeCTable


SET DECIMALS TO 0


USE AToRoman IN 0 ORDER main ALIAS ct


SELECT ct


cRoman = “”


FOR i = 3 TO 0 STEP -1


nAdd=10^i


nChrs=INT(nVal/nAdd)


SEEK nAdd


IF i#3


cRoman=cRoman+ICASE(nChrs=9,ct.nona,;


BETWEEN(nChrs,5,8),ct.penta+REPLICATE(ct.symb,nChrs-5),;


nChrs=4,ct.symb+ct.penta,;


REPLICATE(ct.symb,nChrs))


ELSE


cRoman=cRoman+REPLICATE(ct.symb,nChrs)


ENDIF


nVal=nVal- (nChrs* ct.narabic)


ENDFOR


USE IN ct


?cRoman


 


RETURN


 


 


 


FUNCTION MakeCTable


IF FILE(“AToRoman.DBF”)


RETURN


ENDIF


CREATE TABLE AToRoman(narabic N(4,0), symb C(1),penta C(1), nona C(2))


INSERT INTO AToRoman VALUES (1000,”M”,””,””)


INSERT INTO AToRoman VALUES (100,”C”,”D”,”CM”)


INSERT INTO AToRoman VALUES (10,”X”,”L”,”XC”)


INSERT INTO AToRoman VALUES (1,”I”,”V”,”IX”)


INDEX ON narabic TAG main


USE IN AToRoman


RETURN


 

Comments (3)

  1. Actually John a great use for this would be if you needed to "write" a report that was broken into sections like a Word document.

    Although I would likely recommend using a cursor instead of the physical table (no need in leaving extra tables lying around), eh?

  2. vsdata says:

    Well, true, Andrew, and the cursor if this was a one-shot but if this were real-world, reusable code then I imagine the conversion rules would be a static table.